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

ant*_*ton 4 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 }
Run Code Online (Sandbox Code Playgroud)

如何在 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 }]
    }
Run Code Online (Sandbox Code Playgroud)

ant*_*ton 8

我的解决方案是

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

返回

{
    "_id" : "abc",
    "items" : [
        {
            "score" : 20
        },
        {
            "score" : 15
        }
    ]
}
{
    "_id" : "xyz",
    "items" : [
        {
            "score" : 20
        },
        {
            "score" : 15
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

  • Mongodb 不保证小组阶段会保留以前的排序,在更大的数据集或分片集群上,它会打乱顺序。Afaik 没有办法做到这一点 (2认同)