search

Home  >  Q&A  >  body text

mongodb - Mongo group分组后,怎么对分组后的结果进行从大到小排序,并取前5个

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实现吗?具体怎么写函数呢??或者能用什么方法实现????

怪我咯怪我咯2795 days ago1144

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-24 09:16:07

    To be honest, group-by under mongo is quite troublesome. Native mongo statement, aggregate query through pipeline

    sqldb.term.aggregate([
         {$match:{library_id:3607}},
         {$limit:5},
         {$group:{_id:"$version", count: {$sum:1}}},
         {$sort:{count:-1}}
    ])
    

    term: The name of the collection you want to query
    $match: Matching conditions, optional
    $limit: Number of results, optional
    $group: Aggregation rules
    $sort: Query The results are sorted, -1 means descending order

    http://docs.mongoing.com/manual-zh/reference/operator/aggregation.html#aggregation-pipeline-operator-reference

    reply
    0
  • 高洛峰

    高洛峰2017-04-24 09:16:07

    Use aggregate for group calculation and sorting.
    Simple example

    db.collection.aggregate([  {$group:{_id:"$source",total:{$sum:"$changeValue"}}},{$limit:1}])
    

    See http://docs.mongodb.org/manual/reference/command/aggregate/

    reply
    0
  • Cancelreply