我有一個看起來像這樣的學生集合:如何為每個學生找到最多兩個考試成績
[
{
"_id" : ObjectId("61868aa03b2fe72b58c891a5"),
"name" : "Max",
"examScores" : [
{
"difficulty" : 4,
"score" : 57.9
},
{
"difficulty" : 6,
"score" : 62.1
},
{
"difficulty" : 3,
"score" : 88.5
}
]
},
{
"_id" : ObjectId("61868aa03b2fe72b58c891a6"),
"name" : "Manu",
"examScores" : [
{
"difficulty" : 7,
"score" : 52.1
},
{
"difficulty" : 2,
"score" : 74.3
},
{
"difficulty" : 5,
"score" : 53.1
}
]
}
]
我想使用聚合來回傳兩個最高的examScores.score
像這樣:
[
{
name: "Max",
maxExams: [88.5, 62.1]
},
{
name: "Manu",
maxExams: [74.3, 53.1]
}
]
我嘗試了聚合階段 $project 和 $unwind 和 $sort 但它們都無法解決我的問題
uj5u.com熱心網友回復:
這里是:
mongos> db.s.aggregate([
{$unwind:"$examScores"},
{$sort:{"name":1,"examScores.score":-1}},
{$group:{ _id:"$name" ,Scores:{$push:"$examScores.score"} }},
{$project:{_id:0,name:"$_id",maxExam:{$slice:["$Scores",2]}}}
])
{ "name" : "Manu", "maxExam" : [ 74.3, 53.1 ] }
{ "name" : "Max", "maxExam" : [ 88.5, 62.1 ] }
mongos>
解釋:
- 展開分數,以便您以后可以對它們進行排序。
- 按名稱排序,分數從最大值到最小值
- 將分數分組在新陣列分數中
- 投影名稱和 maxExam(從分數中切出前 2 個)
uj5u.com熱心網友回復:
詢問
- 您可以減少并只保留最多 2 個分數
- 從
[-1,-1]if score >= first member add left(舊的右邊將被洗掉)開始,否則如果 score >= 第二個成員添加右邊(舊的右邊將被洗掉),否則什么都不做 - 如果你想要超過 2-3 個
- 如果
$setWindowFields可以使用MongoDB 5 - else unwind group slice 2 解決方案
- 如果
*在這里你不需要放松/分組/排序等,因為只有 2 個。
測驗代碼在這里
aggregate(
[{"$project":
{"_id": 0,
"name": 1,
"maxExams":
{"$reduce":
{"input": "$examScores",
"initialValue": [-1, -1],
"in":
{"$switch":
{"branches":
[{"case":
{"$gte": ["$$this.score", {"$arrayElemAt": ["$$value", 0]}]},
"then":
{"$concatArrays":
[["$$this.score"], [{"$arrayElemAt": ["$$value", 0]}]]}},
{"case":
{"$gte": ["$$this.score", {"$arrayElemAt": ["$$value", 1]}]},
"then":
{"$concatArrays":
[[{"$arrayElemAt": ["$$value", 0]}], ["$$this.score"]]}}],
"default": "$$value"}}}}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/351318.html
