MongoDB聚合中的'$ push'数组

时间:2022-03-25 17:43:35

Is it possible to sum an array returned from a $push operator within the $group stage?

是否可以对$ group阶段中$ push运算符返回的数组求和?

{
  $group: {
    _id: '$randomId',
    fruitKind: '$fruitId',
    ...,
    ripeness: { $push: {$cond: [ { $eq: [ "$fruitComplexion", "ripe" ] }, 1, 0 ] }}
   }
},
{  
  $project : {
    _id: 1,
   totalRipeFruit : "$ripeness",
  }
}

Right now this simply returns each value in the array: For example,

现在,这只是返回数组中的每个值:例如,

totalRipeFruit: Array[5] -> [0, 1, 1, 0, 1]

However, I am aiming towards simplifying this to return the sum of the array such as (using the previous example):

但是,我的目标是简化这个以返回数组的总和,如(使用前面的例子):

totalRipeFruit: 3 

1 个解决方案

#1


0  

Seems like I figured it out by using the $sum and $add operator instead:

好像我通过使用$ sum和$ add运算符来解决它:

ripeness: { $sum: { $add: {$cond: [ { $eq: [ "$fruitComplexion", "ripe" ] }, 1, 0 ] } } }

#1


0  

Seems like I figured it out by using the $sum and $add operator instead:

好像我通过使用$ sum和$ add运算符来解决它:

ripeness: { $sum: { $add: {$cond: [ { $eq: [ "$fruitComplexion", "ripe" ] }, 1, 0 ] } } }