[英]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.