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

如何在Mongoose中执行聚合查询实现按类型金额求和

正确实现按类型汇总金额的MongoDB聚合查询

问题说明

现有数据集:

[ 
  { type: 'sale' , amount: 2000 }, 
  { type: 'expenditure' , amount: 1300 }, 
  { type: 'sale' , amount: 4090 }, 
  { type: 'expenditure' , amount: 3000 }
]

需要按sale和expenditure类型分别对amount字段求和,期望输出:

[ 
  { type: 'sale' , amount: 6090 }, 
  { type: 'expenditure' , amount: 4300 }
]

错误代码分析

你写的聚合查询存在两个关键问题:

  1. $group阶段缺少分组依据:MongoDB的$group必须通过_id指定分组字段,你直接写type: "sale"会固定分组为sale,无法按数据中的type字段动态分组。
  2. $sum参数格式错误:需要用$amount引用字段值,而非字符串"amount",否则会将字符串视为0进行求和。

正确代码实现

store.aggregate(
  [
    {
      $group: {
        _id: "$type", // 按数据中的type字段值分组
        totalAmount: { $sum: "$amount" } // 计算每个分组的amount总和
      }
    },
    {
      $project: {
        _id: 0, // 隐藏默认的_id字段
        type: "$_id", // 将分组标识转为type字段
        amount: "$totalAmount" // 将求和结果转为amount字段
      }
    }
  ],
  function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  }
);

代码说明

  • $group阶段:通过_id: "$type"按数据中的type值分组,$sum: "$amount"完成每个分组的金额求和。
  • $project阶段:重新格式化输出结构,把分组用的_id映射为type字段,求和结果totalAmount映射为amount字段,同时隐藏默认生成的_id,让输出完全匹配期望格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:55:13