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

Mongoose聚合查询:按客户ID合并两集合统计总额

合并PR与Invoice集合按客户ID统计金额总和的Mongoose聚合方案

核心思路

通过$unionWith合并两个集合的目标字段,再按customerId分组完成金额统计,无需多次查询。

完整聚合查询代码

// 假设PR和Invoice对应的Mongoose模型为PRModel、InvoiceModel
PRModel.aggregate([
  // 筛选PR集合所需字段,标记来源集合
  {
    $project: {
      customerId: 1,
      total_usd: 1,
      _id: 0,
      source: { $literal: 'PR' }
    }
  },
  // 合并Invoice集合的对应数据
  {
    $unionWith: {
      coll: 'invoices', // 填写MongoDB中Invoice集合的实际名称
      pipeline: [
        {
          $project: {
            customerId: 1,
            total_usd: 1,
            _id: 0,
            source: { $literal: 'Invoice' }
          }
        }
      ]
    }
  },
  // 按客户ID分组,分别统计各集合金额及总合计
  {
    $group: {
      _id: '$customerId',
      pr_total: {
        $sum: { $cond: [{ $eq: ['$source', 'PR'] }, '$total_usd', 0] }
      },
      invoice_total: {
        $sum: { $cond: [{ $eq: ['$source', 'Invoice'] }, '$total_usd', 0] }
      },
      grand_total: { $sum: '$total_usd' }
    }
  },
  // 重命名字段让结果更直观
  {
    $project: {
      customerId: '$_id',
      pr_total: 1,
      invoice_total: 1,
      grand_total: 1,
      _id: 0
    }
  }
])
.then(statistics => {
  console.log('统计结果:', statistics);
})
.catch(err => {
  console.error('聚合查询失败:', err);
});

简化版(仅需总合计)

如果不需要单独统计PR和Invoice的金额,可简化分组阶段:

{
  $group: {
    _id: '$customerId',
    grand_total: { $sum: '$total_usd' }
  }
}

注意事项

  • 确保两个集合中客户ID的字段名一致,若不一致(如一个是customer_id),需在$project阶段统一为customerId
  • $unionWith的coll参数需填写MongoDB中的实际集合名称,而非Mongoose模型名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 16:34:56