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

如何在Mongoose中对数组内的amount字段求和?

在Mongoose中计算所有文档数组内字段的总和

要计算所有文档中payments数组里amount字段的总和,你可以借助MongoDB的聚合框架实现,以下是两种高效方案:

方案一:使用$unwind展开数组后求和

通过$unwind将每个文档的payments数组拆分为独立文档,再全局分组累加求和:

// 假设你的Mongoose模型名为Product
Product.aggregate([
  // 展开payments数组,每个数组项转为单独文档
  { $unwind: "$payments" },
  // 全局分组,累加所有amount值
  {
    $group: {
      _id: null,
      amountSum: { $sum: "$payments.amount" }
    }
  },
  // 移除_id字段,只保留结果字段
  { $project: { _id: 0 } }
])
.then(result => {
  console.log(result[0]); // 输出 { amountSum: 65 }
})
.catch(err => {
  console.error(err);
});

方案二:使用$reduce在文档内先求和再全局累加

无需展开数组,先通过$reduce计算单个文档内payments数组的amount总和,再全局累加所有文档的结果,性能更优:

Product.aggregate([
  {
    $group: {
      _id: null,
      amountSum: {
        $sum: {
          $reduce: {
            input: "$payments",
            initialValue: 0,
            in: { $add: ["$$value", "$$this.amount"] }
          }
        }
      }
    }
  },
  { $project: { _id: 0 } }
])
.then(result => {
  console.log(result[0]);
})
.catch(err => {
  console.error(err);
});

注意事项

如果存在payments数组为空、不存在,或amount字段为null的情况,可通过$ifNull处理避免求和错误:将"$$this.amount"替换为{ $ifNull: ["$$this.amount", 0] }即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:20:25