首页 > 解决方案 > mongodb $sum 只有正数

问题描述

是他们的一种方式,我可以只对正数求和,并避免在我的 MongoDB 聚合查询中使用负数,即

aggregate([
      {
        $match: { },
      },
      { $group: { _id: '$id',  total: { $sum: '$amount' } } },
    ])

标签: node.jsmongodbmongodb-queryaggregation-framework

解决方案


您可以使用$cond运算符,并且只需$sum 0在数字为负数时使用:

{ $group: { _id: '$id',  total: { $sum: { $cond: [ { $gt: [ '$amount', 0 ] }, '$amount', 0 ]  } } } }

推荐阅读