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
相关产品推荐
相关产品推荐

