我有一個物件陣列,需要在管道輸出的欄位中包含值的總計。
[
{
"_id": NumberInt(1),
"absences": 170.0,
"dayNumber": NumberInt(1),
"dayName": "Sunday"
},
{
"_id": NumberInt(2),
"absences": 130.0,
"dayNumber": NumberInt(2),
"dayName": "Monday"
}
]
我想要的結果包括totalAbsences密鑰,它總結了所有檔案的缺席。
[
{
"_id": 1,
"absences": 170,
"dayName": "Sunday",
"dayNumber": 1,
"totalAbsences": 300
},
{
"_id": 2,
"absences": 130,
"dayName": "Monday",
"dayNumber": 2,
"totalAbsences": 300
}
]
我可以使用下面的代碼獲得總計,但我丟失了管道中的所有其他值。如何添加totalAbsences到每個檔案并保留已在管道中的內容?這個Mongo Playground有一個資料模擬。
{
_id: null,
total: {
$sum: "$absences"
}
}
uj5u.com熱心網友回復:
在 MongoDB 5.0 版中,您可以使用新的$setWindowFields(),它更簡單,而且很可能也更快:
db.collection.aggregate([
{
$setWindowFields: {
output: {
totalAbsences: { $sum: "$absences" }
}
}
}
])
uj5u.com熱心網友回復:
db.collection.aggregate([
{
$group: {
_id: null,
total: {
$sum: "$absences"
},
items: {
$push: "$$ROOT"
}
}
},
{
$unwind: "$items"
},
{
$replaceRoot: {
"newRoot": {
$mergeObjects: [
{
total: "$total"
},
"$items"
]
}
}
}
])
mongoplayground
uj5u.com熱心網友回復:
您可以使用$firstwith$$ROOT來保存檔案。
{
_id: '$orgId',
total: {
$sum: '$createdAt'
},
"doc": { "$first": "$$ROOT" }
}
之后,您可以使用$replaceRoot和$mergeObjects。
{
newRoot: { $mergeObjects : [{ total: '$total' }, '$doc']}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399230.html
