node.js - mongodb $sum 只有正数
问题描述
是他们的一种方式,我可以只对正数求和,并避免在我的 MongoDB 聚合查询中使用负数,即
aggregate([
{
$match: { },
},
{ $group: { _id: '$id', total: { $sum: '$amount' } } },
])
解决方案
您可以使用$cond运算符,并且只需$sum
0
在数字为负数时使用:
{ $group: { _id: '$id', total: { $sum: { $cond: [ { $gt: [ '$amount', 0 ] }, '$amount', 0 ] } } } }
推荐阅读
- svg - SVG 十进制颜色值(0 到 1)如何转换为(0 到 255)颜色值?
- reactjs - 如何构建通用打字稿自定义钩子?
- salesforce-marketing-cloud - 同步数据扩展上的 AMPscript lookuprows 错误
- php - 共享主机中的 Web 专用 IP
- git - Gitlab:服务器挂钩自定义错误消息未显示在合并请求上
- java - 在 android studio 的应用购买中设置问题
- certificate-pinning - 证书固定和转换 isrg-root 让我们加密
- javascript - chart.js - 轴选项问题 - 我做错了什么?
- android - 浮动操作按钮不改变布局
- mongodb - Mongo 在集合中的某个索引处获取 10 个文档