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

如何利用MongoDB+Mongoose按sellerId计算卖家订单总收入?

按sellerId计算卖家订单总金额的MongoDB聚合方案

核心思路

由于sellerId嵌套在订单的products数组中,需先拆解数组建立卖家与订单金额的关联,再按卖家ID分组求和:

  1. 拆解数组:用$unwind将每个订单的products数组拆分为单独文档,确保每个sellerId对应一条订单记录;
  2. 分组求和:通过$group按sellerId分组,累加对应订单的amount得到总金额;
  3. 字段优化(可选):用$project调整输出字段名,让结果更直观。

Mongoose代码实现

Order.aggregate([
  // 拆解products数组,每个product生成独立文档
  { $unwind: "$products" },
  // 按sellerId分组,计算总金额与总税费
  {
    $group: {
      _id: "$products.sellerId",
      totalAmount: { $sum: "$amount" },
      totalTax: { $sum: "$tax" }
    }
  },
  // 重命名字段,隐藏默认_id
  {
    $project: {
      sellerId: "$_id",
      totalAmount: 1,
      totalTax: 1,
      _id: 0
    }
  }
])
.then(result => console.log(result))
.catch(err => console.error(err));

输出结果

基于你提供的订单数据,执行后会得到:

[
  {
    "sellerId": "6360c6ed05e1e99034b5f7eb",
    "totalAmount": 99,
    "totalTax": 0.99
  },
  {
    "sellerId": "6360d4d5bd860240e258c582",
    "totalAmount": 11,
    "totalTax": 0.11
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:41:26