【发布时间】:2021-12-29 02:38:05
【问题描述】:
我有一个对象数组,需要在管道输出的字段中包含总的值。
[
{
"_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
}
]
我可以使用下面的代码get the grand total,但我会丢失管道中的所有其他值。如何将totalAbsences 添加到每个文档并保留已在管道中的内容?这个Mongo Playground 模拟了数据。
{
_id: null,
total: {
$sum: "$absences"
}
}
【问题讨论】:
标签: mongodb aggregation-framework