[英]How to find the sum of values that are inside a nested array using mongodb aggregation?
[英]Sum '$push' array within MongoDB aggregation
是否可以在$group
阶段对从$push
运算符返回的数组求和?
{
$group: {
_id: '$randomId',
fruitKind: '$fruitId',
...,
ripeness: { $push: {$cond: [ { $eq: [ "$fruitComplexion", "ripe" ] }, 1, 0 ] }}
}
},
{
$project : {
_id: 1,
totalRipeFruit : "$ripeness",
}
}
现在,这只是返回数组中的每个值:例如,
totalRipeFruit: Array[5] -> [0, 1, 1, 0, 1]
但是,我的目标是简化此过程以返回数组的总和,例如(使用前面的示例):
totalRipeFruit: 3
似乎我是通过使用$sum
和$add
运算符来解决的:
ripeness: { $sum: { $add: {$cond: [ { $eq: [ "$fruitComplexion", "ripe" ] }, 1, 0 ] } } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.