在生產服務器上我使用 mongodb 4.4
我有一個運行良好的查詢
db.step_tournaments_results.aggregate([
{ "$match": { "tournament_id": "6377f2f96174982ef89c48d2" } },
{ "$sort": { "total_points": -1, "time_spent": 1 } },
{
$group: {
_id: "$club_name",
'total_points': { $sum: "$total_points"},
'time_spent': { $sum: "$time_spent"}
},
},
])
但問題出在 $group 運算子中,因為它將每個組的所有點相加以獲得 total_points,但我只需要每個組中最好的 5 個。如何實作?
uj5u.com熱心網友回復:
詢問
- 喜歡你的查詢,匹配和排序
- 在 group 而不是 sum 上,將所有成員收集在一個陣列中(我收集了,但如果檔案有很多欄位,
$ROOT你只能收集 ??a 中你需要的 2 個欄位){} - 取其中的前5個
- 從前 5 個中取出你需要的 2 個
- 洗掉臨時欄位
*使用 mongodb 6,您可以在組中執行此操作,而無需在陣列中收集成員,在 mongodb 5 中,您也可以在沒有組的情況下使用視窗欄位,但對于 mongodb 4.4,我認為這是一種方法它
aggregate(
[{"$match": {"tournament_id": {"$eq": "6377f2f96174982ef89c48d2"}}},
{"$sort": {"total_points": -1, "time_spent": 1}},
{"$group": {"_id": "$club_name", "group-members": {"$push": "$$ROOT"}}},
{"$set":
{"first-five": {"$slice": ["$group-members", 5]},
"group-members": "$$REMOVE"}},
{"$set":
{"total_points": {"$sum": "$first-five.total_points"},
"time_spent": {"$sum": "$first-five.time_spent"},
"first-five": "$$REMOVE"}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537283.html
標籤:数据库聚合框架
上一篇:我將如何通過使用MongoDB聚合進行查詢來制作分組串列?
下一篇:無法匹配陣列中的物件
