我正在嘗試對一個簡單的物件陣列進行排序,但我正在努力解決它。我閱讀了幾篇關于如何做到這一點的帖子,其中許多人建議先 $unwind the array 然后 $sort 然后 $group ... 但它對我不起作用,因為在 group 之后我失去了“name” porpertie
這是我的檔案:
{
"_id" : 1,
"name" : "Aurelia Menendez",
"scores" : [
{
"type" : "exam",
"score" : 60.06045071030959
},
{
"type" : "quiz",
"score" : 52.79790691903873
},
{
"type" : "homework",
"score" : 71.76133439165544
},
{
"type" : "homework",
"score" : 34.85718117893772
}
]
}
我正在嘗試這個
{ $unwind: '$scores' },
{ $sort: { 'score': 1 } },
{
$group: {
_id: '$_id',
scores: { $push: '$scores' }
}
}
預期輸出
{
"_id" : 1,
"name" : "Aurelia Menendez",
"scores" : [
{
"type" : "homework",
"score" : 71.76133439165544
},
{
"type" : "exam",
"score" : 60.06045071030959
},
{
"type" : "quiz",
"score" : 52.79790691903873
},
{
"type" : "homework",
"score" : 34.85718117893772
}
]
}
uj5u.com熱心網友回復:
詢問
- 您的查詢有小的變化和
$first額外的累加器 - 所有 id 都將具有相同的名稱,因為它們屬于展開前的第一個 1 個檔案,因此我們只取一個(第一個)
測驗代碼在這里
aggregate(
[{"$unwind": {"path": "$scores"}},
{"$sort": {"scores.score": -1}},
{"$group":
{"_id": "$_id",
"name": {"$first": "$name"},
"scores": {"$push": "$scores"}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/361383.html
