这个问题在这里已经有了答案:





mongodb group values by multiple fields

(3 个回答)


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

请您参考如下方法:

我的解决方案是

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


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!