java 操作mongoDB执行group by
程序员文章站
2022-03-05 13:05:33
...
最近公司要用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" }
执行mongo的SQL大概是
- db.consume.group({ key:{"user_id":true} ,cond:{"consume.time":{$gt:"1314583316",$lt:"1314583336"}},initial:{co:0},reduce:function(oj,pr){pr.co++} } )
java代码是
- 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);
然后去一下size
看了下mongo的doc发现还有
- List list = userSColl.distinct("user_id", new BasicDBObject("consume.time",new BasicDBObject("$gt","1314583316").append("$lt", "1314583336")));
转自: http://dasimm.iteye.com/blog/1632959
上一篇: PHP扩展之XML操作(五)——XMLWriter
下一篇: 数据库查询结果的动态排序(1)