MongoDB组对每个组进行排序和限制

时间:2017-09-08 08:21:31

标签: mongodb

例如我有一个集合:

{ "_id" : 1, "name" : "abc", "score" : 10 }
{ "_id" : 2, "name" : "abc", "score" : 15 }
{ "_id" : 3, "name" : "abc", "score" : 20 }
{ "_id" : 4, "name" : "xyz", "score" : 10 }
{ "_id" : 5, "name" : "xyz", "score" : 15 }
{ "_id" : 6, "name" : "xyz", "score" : 20 }

如何在Mongodb中执行查询,按name分组,然后按score排序,并将其与limit=2一起分组。我想这样:

    {"_id": "abc", "items": [
          { "_id" : 3, "name" : "abc", "score" : 20 },
          { "_id" : 2, "name" : "abc", "score" : 15 }]
    }
    {"_id": "xyz", "items": [
          { "_id" : 6, "name" : "xyz", "score" : 20 },
          { "_id" : 5, "name" : "xyz", "score" : 15 }]
    }

2 个答案:

答案 0 :(得分:3)

我的解决方案是

db.collection.aggregate([
    {$sort:{name:-1, score:-1}},
    {$group:{_id:"$name",items:{$push:{score:"$score"}}}}, 
    {$project:{items:{$slice:["$items", 2]}}}])
.pretty()

返回

{
    "_id" : "abc",
    "items" : [
        {
            "score" : 20
        },
        {
            "score" : 15
        }
    ]
}
{
    "_id" : "xyz",
    "items" : [
        {
            "score" : 20
        },
        {
            "score" : 15
        }
    ]
}

答案 1 :(得分:-1)

试试这个。

  unwind = { "$unwind" : "$score" };

  sort = { "$sort" : { "score" : -1 } };

  group = {
      "$group" : {
          "_id" : "$name",
          "scores" : {
              "$push" : {
                  "_id": "$_id",
                  "score": "$score",
                  "name": "$name"
              }
          }
      }
   }

  project = {
    "$project" : {
        "_id" : "$_id",
        "items" : {
            "$slice" : ["$scores",0,2]
        }
    }
  }  

db.collection.aggregate([unwind,sort,group,project]).pretty()