MongoDB 聚合运算group及map reduce

1.db.collection.group

   arice:PRIMARY> db.t.find(){"_id":ObjectId("51244a9e181fee7a28391f2a"),"hours":"8","ts":ISODate("2012-01-08T16:00:00Z"),"name":"ccj"}{"_id":ObjectId("51244afa181fee7a28391f2b"),"hours":"5","ts":ISODate("2012-01-09T16:00:00Z"),"name":"ccj"}{"_id":ObjectId("51244afa181fee7a28391f2c"),"hours":"3","ts":ISODate("2012-01-10T16:00:00Z"),"name":"ccj"}{"_id":ObjectId("51244afa181fee7a28391f2d"),"hours":"1","ts":ISODate("2012-02-09T16:00:00Z"),"name":"ccj"}{"_id":ObjectId("51244afa181fee7a28391f2e"),"hours":"8","ts":ISODate("2012-01-08T16:00:00Z"),"name":"inosql"}{"_id":ObjectId("51244afa181fee7a28391f2f"),"hours":"4","ts":ISODate("2012-01-09T16:00:00Z"),"name":"inosql"}{"_id":ObjectId("51244afa181fee7a28391f30"),"hours":"3","ts":ISODate("2012-01-10T16:00:00Z"),"name":"inosql"}{"_id":ObjectId("51244afc181fee7a28391f31"),"hours":"2","ts":ISODate("2012-02-09T16:00:00Z"),"name":"inosql"}
    arice:PRIMARY>  db.t.group({...    keyf:function(doc){...var t =newDate(doc.ts);...return{name_ym:doc.name+":"+...                     t.getFullYear()+"-"+(t.getMonth()+1)};...},...    initial:{sum:0},...    reduce:function(doc,agg){agg.sum+=NumberInt(doc.hours);}...});[{"name_ym":"ccj:2012-1","sum":16},{"name_ym":"ccj:2012-2","sum":1},{"name_ym":"inosql:2012-1","sum":15},{"name_ym":"inosql:2012-2","sum":2}]

2.aggregate

match匹配查询条件,group by uuid

db.bindingfailure.aggregate({$match:{"created":{$gte:ISODate("2013-07-20T00: 00: 00.0Z"),$lte:ISODate("2013-07-20T23: 59: 59.0Z")},"platform":"android"}},{$group:{_id:"$uuid",count:{$sum:1}}})...{"_id":"866278011448789-C46AB769C063","count":4},{"_id":"A0000042E687A3-70723cd898e2","count":4},{"_id":"860312026895795-acf7f3e2f423","count":4}],"ok":1}

统计上述uuid count>1的数目

db.bindingfailure.aggregate({$match:{"created":{$gte:ISODate("2013-07-20T00: 00: 00.0Z"),$lte:ISODate("2013-07-20T23: 59: 59.0Z")},"platform":"android"}},{$group:{_id:"$uuid",count:{$sum:1}}},{$match:{count:{$gt:1}}},{$group:{_id:null,count:{$sum:1}}}){"result":[{"_id":null,"count":1223}],"ok":1}

统计上述uuid count=1的数目

 db.bindingfailure.aggregate({$match:{"created":{$gte:ISODate("2013-07-20T00: 00: 00.0Z"),$lte:ISODate("2013-07-20T23: 59: 59.0Z")},"platform":"android"}},{$group:{_id:"$uuid",count:{$sum:1}}},{$match:{count:1}},{$group:{_id:null,count:{$sum:1}}}){"result":[{"_id":null,"count":469}],"ok":1}

MongoDB 聚合运算group及map reduce,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。