我有以下集合,其中字段的数量随时间而变化。
{
"_id" : "9235@7421",
"usine" : { "0" : 0, "1" : 3, "2" : 1, "3" : 2, "4" : 0, "5" : 3, "6" : 1, "7" : 0, "8" : 2, "9" : 1 },
"ecole" : { "0" : 1, "1" : 0, "2" : 0, "3" : 1, "4" : 1, "5" : 0, "6" : 0, "7" : 1, "8" : 0, "9" : 1 }
}
以下查询工作正常。它计算所有字段的值之和。
db.lieux.aggregate([
{
$match: {
"_id": "9235@7421"
}
},
{
$project: {
"MontoSum": {
$sum: {
$add: [
"$usine.0", "$usine.1", "$usine.2", "$usine.3", "$usine.4", "$usine.5", "$usine.6", "$usine.7", "$usine.8", "$usine.9", "$ecole.0", "$ecole.1", "$ecole.2", "$ecole.3", "$ecole.4", "$ecole.5", "$ecole.6", "$ecole.7", "$ecole.8", "$ecole.9"]
}
}
}
}
])
The result is: { "_id" : "9235@7421", "MontoSum" : 18 }
and this is correct.
我的问题是:
1)有没有更好的方法来查询我的集合的字段的值的总和?我觉得我的查询时间太长,一点都不聪明。
2)当文档缺少我查询中的字段(例如,字段“ 6”丢失)时,返回的值为{“ _id”:“ 9235 @ 7421”,“ MontoSum”:0},这是不正确的。在我看来,sum函数不喜欢缺少字段。在我的情况下,如何使用诸如$ ifNull之类的东西?
非常感谢你
现在,这并不是最短的表达式,但是可以扩展。