当数组字段可能完全丢失时(如第 10 个月的情况),如何让 MongoDB 计算数组值的总和?
例如:
> db.month.save({MonthNum: 10,
... NumWeekdays: 23});
> db.month.save({MonthNum: 11,
... NumWeekdays: 21,
... Holidays: [ {Description: "Thanksgiving", NumDays: 2} ] });
> db.month.save({MonthNum: 12,
... NumWeekdays: 22,
... Holidays: [ {Description: "Christmas", NumDays: 6},
... {Description: "New Year's Eve", NumDays: 1} ] });
> db.month.aggregate( { $unwind: "$Holidays" },
... { $group: { _id: "$MonthNum",
... total: { $sum: "$Holidays.NumDays" } } });
{
"result" : [
{
"_id" : 12,
"total" : 7
},
{
"_id" : 11,
"total" : 2
}
],
"ok" : 1
}
如何让第 10 个月显示在上述结果中(将“总计”显示为 0)?
奖励:我如何让上面显示可用的工作日(NumWeekdays 减去假期的总和)?
我已经尝试 $project 首先将数据转换为规范格式,但到目前为止没有成功......谢谢!