【发布时间】:2020-11-10 10:36:05
【问题描述】:
我有一个文档,其中包含从根目录嵌套一层的数字数组。我想减少数组的总和并聚合所有这些数组的总和。例如,在下面的集合中,我希望返回 { votes: 12 }。
{
userId: 1,
stats: {
votes: [0, 4, 1, 0, 2]
}
},
{
userId: 2,
stats: {
votes: [0, 2, 2, 0, 1]
}
}
我正在尝试减少聚合管道中的总和,但不断得到 0 或 N*initialValue 结果。
{ $group: {
votes: { $sum: { $reduce: { input: '$stats.votes', initialValue: 0, in: { $add : ["$$value", "$$this"] } } } },
} },
我一直在查看 $sum、$reduce 和 $add 的 Mongo 聚合文档,但似乎无法弄清楚。
【问题讨论】:
标签: node.js mongodb aggregation-framework