0
我正在嘗試新建mongodb,並嘗試爲集合mytest1中的學生拔出具有最高標記的文檔,並在下方形成了一個查詢。基於關鍵值對文檔進行排序和排序?
{
"_id" : ObjectId("5943b63496459374d40da429"),
"name" : "Person1",
"marks" : 20
},
{
"_id" : ObjectId("5943b65196459374d40da43a"),
"name" : "Person2",
"marks" : 20
},
{
"_id" : ObjectId("5943b65196459374d40da43c"),
"name" : "Person1",
"marks" : 30
},
{
"_id" : ObjectId("5943b6d696459374d40da47a"),
"name" : "Person1",
"marks" : 25
},
{
"_id" : ObjectId("5943b6d696459374d40da47c"),
"name" : "Person2",
"marks" : 50
},
{
"_id" : ObjectId("5943b6d696459374d40da47e"),
"name" : "Person1",
"marks" : 90
},
{
"_id" : ObjectId("5943b6d696459374d40da480"),
"name" : "Person3",
"marks" : 990
}
查詢:
db.mytest1.aggregate([
{ $sort : { "name" : 1,"marks" : -1} },
{$group:
{
_id: "$name",
name: { $first: "$name" },
marks: { $first: "$marks" }
}}
])
- 有沒有更好的方式來做到這一點?
- 如果我的方案是基於標記對文檔進行編號,我該如何實現它?
結果:
{"name" : "Person1","marks" : 30,"rank" : 1}
{"name" : "Person1","marks" : 25,"rank" : 2}
{"name" : "Person1","marks" : 20,"rank" : 3}
{"name" : "Person2","marks" : 50,"rank" : 1}
{"name" : "Person2","marks" : 20,"rank" : 2}
{"name" : "Person3","marks" : 990,"rank" : 3}