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

MongoDB:如何在数组字段的$sum中使用$toInt?

MongoDB计算嵌套数组字段总和的正确方法

你的报错原因是$toInt只能转换单个值,而$transactions.fee返回的是一个字符串数组,直接传给$toInt会触发类型转换错误。

要实现计算所有交易手续费总和的需求,需要先将数组中每个fee字符串转为整数,再求和,以下是两种可行方案:

方案1:使用$map + $sum

通过$map遍历transactions数组,把每个元素的fee字段转为整数,再用$sum对转换后的整数数组求和:

$addFields: {
  total_fee: {
    $sum: {
      $map: {
        input: "$transactions",
        as: "tx",
        in: { $toInt: "$$tx.fee" }
      }
    }
  }
}

方案2:使用$reduce

通过$reduce累加每个交易的手续费,初始值设为0,每次迭代将当前交易的fee转成整数后加到累计值上:

$addFields: {
  total_fee: {
    $reduce: {
      input: "$transactions",
      initialValue: 0,
      in: { $add: ["$$value", { $toInt: "$$this.fee" }] }
    }
  }
}

如果需要批量更新集合中所有文档的total_fee字段,可以结合updateMany使用管道更新:

db.yourCollectionName.updateMany(
  {},
  [
    {
      $addFields: {
        total_fee: {
          $sum: {
            $map: {
              input: "$transactions",
              as: "tx",
              in: { $toInt: "$$tx.fee" }
            }
          }
        }
      }
    }
  ]
)

内容的提问来源于stack exchange,提问作者Đỗ Quý Anh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:07:17