BasicDBObject key = new BasicDBObject("ip",true);
BasicDBObject initial = new BasicDBObject("count",0);
BasicDBObject cond = 。。。。
String reduce = "function(obj,prev){prev.count+=1}";
String finalize =?????
col.group(key,initial,cond,reduce,finalize);
最后的结果,我想要count
数量从大到小排列,并且只取前五个,能用finalize
实现吗?具体怎么写函数呢??或者能用什么方法实现????
迷茫2017-04-24 09:16:07
老实说,mongo下面的group-by还是比较麻烦的。原生mongo语句,通过管道聚合查询
sql
db.term.aggregate([ {$match:{library_id:3607}}, {$limit:5}, {$group:{_id:"$version", count: {$sum:1}}}, {$sort:{count:-1}} ])
term:你要查询的集合名称
$match:匹配条件,可选
$limit:结果条数,可选
$group:聚合规则
$sort:对查询结果排序,-1表示降序
http://docs.mongoing.com/manual-zh/reference/operator/aggregation.html#aggregation-pipeline-operator-reference
高洛峰2017-04-24 09:16:07
使用aggregate进行分组计算并排序。
简单实例
db.collection.aggregate([ {$group:{_id:"$source",total:{$sum:"$changeValue"}}},{$limit:1}])
参阅http://docs.mongodb.org/manual/reference/command/aggregate/