按组排序并限制每个组的MongoDB分组

4
例如,我有一个集合:
{ "_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 }]
    }
1个回答

11

我的解决方案是

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
        }
    ]
}

4
MongoDB不能保证在group阶段之前的排序顺序被保留,当处理更大的数据集或分片集群时,它可能会混乱无序。据我所知,没有方法可以解决这个问题。 - Angivare
我现在正处于这个阶段的困境中,我的分组操作每次都返回随机结果集。 - abdul rashid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接