java 操作mongoDB执行group by
最近公司要用Mongodb,学习了一下。
关于mongo的group by的用法有一个实例,写下来防止时间长了忘了。
具体的要求是要查询一段时间内消费的会员的总数,要求去重
表结构大致是
{user_id, ......, consume{ ...., time, .... },...}
> db.consume.find({"consume.time.":{$gt:"0"}},{_id:0,user_id:1,"consume.time":1}).sort({"consuem.time":1}).limit(5);{ "consume" : { "time" : "1314583316" }, "user_id" : "34800268" }{ "consume" : { "time" : "1314583319" }, "user_id" : "67400937" }{ "consume" : { "time" : "1314583321" }, "user_id" : "130041511" }{ "consume" : { "time" : "1314583328" }, "user_id" : "4450046611" }{ "consume" : { "time" : "1314583336" }, "user_id" : "20036266" }
db.consume.group({ key:{"user_id":true} ,cond:{"consume.time":{$gt:"1314583316",$lt:"1314583336"}},initial:{co:0},reduce:function(oj,pr){pr.co++} } )
DBCollection userSColl = MongoDBUtils.getDBCollection("consume");BasicDBObject key = new BasicDBObject("user_id",true);BasicDBObject cond = new BasicDBObject("consume.time",new BasicDBObject("$gt","1314583316").append("$lt", "1314583336"));BasicDBObject initial = new BasicDBObject("cou",0);String reduce = "function(obj,pre){pre.cou++}";BasicDBList returnList = (BasicDBList)userSColl.group(key, cond, initial, reduce);
List list = userSColl.distinct("user_id", new BasicDBObject("consume.time",new BasicDBObject("$gt","1314583316").append("$lt", "1314583336")));