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

MongoDB聚合管道中如何对对象数组内的值求和

MongoDB聚合管道中为数组内每个对象添加求和字段的正确实现

你的问题核心是要遍历数组内的每个对象,对单个对象的两个数值字段求和,而非对整个数组的字段集合做运算。原写法直接引用数组字段会导致操作的是整个数组的字段集合,而非单个元素,因此无法得到正确结果。

正确的聚合管道写法

db.collection.aggregate([
  {
    $set: {
      "result.invoices": {
        $map: {
          input: "$result.invoices",
          as: "item",
          in: {
            $mergeObjects: [
              "$$item",
              { total: { $add: ["$$item.amount", "$$item.tax"] } }
            ]
          }
        }
      }
    }
  }
])

代码说明

  • $map:遍历$result.invoices数组,用$$item指代当前迭代的数组元素(即每个invoice对象)
  • $mergeObjects:将原invoice对象($$item)和新生成的total字段合并,保留原有的所有字段
  • $add:对当前元素的amount和tax字段做数值求和,赋值给total

执行结果

执行后会得到你期望的结构:

[
  {
    "result": {
      "invoices": [
        {
          "product": "baseball",
          "amount": 4,
          "tax": 1,
          "total": 5
        },
        {
          "product": "basketball",
          "amount": 10,
          "tax": 2,
          "total": 12
        }
      ]
    }
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 14:04:54