You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合中如何计算countItems1与countItems2的和得到countItems3?

MongoDB聚合中计算两个字段的和作为countItems3

你可以直接使用MongoDB的$add运算符来计算countItems1和countItems2的和,赋值给countItems3。因为$addFields阶段中,同一阶段内定义的字段可以互相引用,写法如下:

...    
$addFields: {
    countItems1: {
        $sum: {
             $map: {
                  input: '$lookupedCollection',
                  in: {
                      $size: {$ifNull: ['$$this.arr1', []]}
                  }
             }
        }
    },
    countItems2: {
        $sum: {
             $map: {
                  input: '$lookupedCollection',
                  in: {
                      $size: {$ifNull: ['$$this.arr2', []]}
                  }
             }
        }
    },
    countItems3 : { $add: ['$countItems1', '$countItems2'] }
}

$add运算符会将传入的数值类型字段相加,这里正好匹配countItems1和countItems2的数值类型,直接得到两者的和。

内容的提问来源于stack exchange,提问作者Roman Nozhenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:15:37