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

MongoDB聚合:仅对type为buy的文档计算平均及统计值

解决方案:MongoDB聚合中仅对type: 'buy'的文档计算总和与平均值

要实现仅对type: 'buy'的文档计算totalBuyPrice和totalBuyAmount,核心是用MongoDB的$cond条件操作符,在$sum表达式里添加判断逻辑——当文档类型符合要求时计算对应值,否则返回0,这样求和时就只会累加符合条件的数据。

完整聚合代码

db.collection.aggregate([
  {
    $group: {
      _id: "$item",
      totalBuyPrice: {
        $sum: {
          $cond: {
            if: { $eq: ["$type", "buy"] },
            then: { $multiply: ["$priceEach", "$amount"] },
            else: 0
          }
        }
      },
      totalBuyAmount: {
        $sum: {
          $cond: {
            if: { $eq: ["$type", "buy"] },
            then: "$amount",
            else: 0
          }
        }
      },
      totalAmount: { $sum: "$amount" }
    }
  },
  {
    $project: {
      _id: 1,
      avgBuyPrice: {
        $divide: ["$totalBuyPrice", "$totalBuyAmount"]
      },
      totalAmount: 1
    }
  }
])

关键逻辑说明

  • totalBuyPrice:通过$cond判断文档type是否为buy,若是则计算priceEach与amount的乘积并加入总和,否则加0。
  • totalBuyAmount:同理,仅当type为buy时累加amount的值,不符合条件则加0。
  • totalAmount:保持原逻辑,累加所有文档的amount(包含sell类型的负数)。
  • $project阶段:用totalBuyPrice除以totalBuyAmount得到该item的平均购买价格,同时返回item编号和总数量。

预期输出(基于示例文档)

[
  {
    "_id": 555,
    "avgBuyPrice": 100000,
    "totalAmount": 1
  },
  {
    "_id": 384,
    "avgBuyPrice": 63333.333333333336,
    "totalAmount": 2
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:33:32