原数据:

/* 1 */
{
"_id" : ObjectId("552a330e05c27486b9b9b650"),
"_class" : "com.mongo.model.Orders",
"onumber" : "002",
"date" : ISODate("2014-01-03T16:03:00.000Z"),
"cname" : "zcy",
"item" : {
"quantity" : 1.0,
"price" : 4.0,
"pnumber" : "p002"
}
} /* 2 */
{
"_id" : ObjectId("552a331d05c275d8590a550d"),
"_class" : "com.mongo.model.Orders",
"onumber" : "003",
"date" : ISODate("2014-01-04T16:03:00.000Z"),
"cname" : "zcy",
"item" : {
"quantity" : 10.0,
"price" : 2.0,
"pnumber" : "p001"
}
} /* 3 */
{
"_id" : ObjectId("552a333105c2f28194045a72"),
"_class" : "com.mongo.model.Orders",
"onumber" : "003",
"date" : ISODate("2014-01-04T16:04:00.000Z"),
"cname" : "zcy",
"item" : {
"quantity" : 30.0,
"price" : 4.0,
"pnumber" : "p002"
}
} /* 4 */
{
"_id" : ObjectId("552a333f05c2b62c01cff50e"),
"_class" : "com.mongo.model.Orders",
"onumber" : "004",
"date" : ISODate("2014-01-05T16:03:00.000Z"),
"cname" : "zcy",
"item" : {
"quantity" : 5.0,
"price" : 4.0,
"pnumber" : "p002"
}
}

  

一。mongo语句

db.orders.group({
key:{date:1,"item.pnumber" : 1},
initial:{"total":0},
reduce:function Reduce(doc,out){
out.total+=doc.item.price
}
})

  

mongo学习-group操作以及java代码-LMLPHP

对out数据进一步处理

db.orders.group({
key: {
date: 1
},
initial: {
"total": 0,
"money":0
},
reduce: function Reduce(doc, out) {
out.total += doc.item.quantity;
out.money += doc.item.price*doc.item.quantity
},
finalize:function Finalize(out){
out.avg=out.money/out.total
return out } })

  

mongo学习-group操作以及java代码-LMLPHP

keyf :对分组字段先进行处理然后分组

db.orders.group({
keyf: function keysss(doc){
return {"month":doc.date.getDay()+1}
},
initial: {
"total": 0,
"money":0
},
reduce: function Reduce(doc, out) {
out.total += doc.item.quantity;
out.money += doc.item.price*doc.item.quantity
},
finalize:function Finalize(out){
out.avg=out.money/out.total
return out
} })

  mongo学习-group操作以及java代码-LMLPHP

java代码:

@Test
public void group(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:111.xml");
MongoTemplate mongoTemplate= (MongoTemplate) applicationContext.getBean("mongoTemplate");
GroupBy groupBy=new GroupBy("date");
BasicDBObject basicDBObject=new BasicDBObject();
basicDBObject.put("total",0);
basicDBObject.put("money",0);
groupBy.initialDocument(basicDBObject);
groupBy.reduceFunction("function Reduce(doc, out) {out.total += doc.item.quantity;out.money += doc.item.price*doc.item.quantity}");
groupBy.finalizeFunction("function Finalize(out){\n" +
" out.avg=out.money/out.total\n" +
" return out\n" +
" }");
// groupBy.finalizeFunction("function Finalize(out) {out.avg = out.money / out.totalreturn out}");
GroupByResults<Object> orders = mongoTemplate.group("orders", groupBy, Object.class); }

  

05-11 16:06