例如我有一个集合:
{ "_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)
我的解决方案是
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)
| 归档时间: |
|
| 查看次数: |
6382 次 |
| 最近记录: |