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

MongoDB按条件统计字段和:Mongoose按type分组统计已付/未付金额

Mongoose 聚合查询实现方案

你可以直接使用 MongoDB 聚合管道完成该统计需求,完整查询逻辑如下:

// 假设你的集合对应 Model 命名为 Order
const statResult = await Order.aggregate([
  // 展开orderPayment数组,将每个子项转为独立文档
  { $unwind: "$orderPayment" },
  // 按type字段分组,分别统计已支付、未支付总额
  {
    $group: {
      _id: "$type",
      paid: {
        $sum: {
          // 条件判断:paid为true时累加paymentSum,否则加0
          $cond: [{ $eq: ["$orderPayment.paid", true] }, "$orderPayment.paymentSum", 0]
        }
      },
      noPaid: {
        $sum: {
          $cond: [{ $eq: ["$orderPayment.paid", false] }, "$orderPayment.paymentSum", 0]
        }
      }
    }
  },
  // 可选步骤:将结果转为你要求的key为type值的对象格式
  {
    $group: {
      _id: null,
      items: {
        $push: {
          k: "$_id",
          v: { paid: "$paid", noPaid: "$noPaid" }
        }
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: { $arrayToObject: "$items" }
    }
  }
])

// 最终你需要的结果为 statResult[0]
console.log(statResult[0])

补充说明

  • 如果你的集合数据量较大,建议给type字段添加索引,大幅提升聚合查询效率
  • 如果存在orderPayment为空数组的记录,可以在聚合最开头添加{ $match: { orderPayment: { $ne: [] } } }步骤过滤无效数据,减少计算量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:36:04