MongoDB聚合查询如何同时统计全局总和及支付方式分组金额
MongoDB 聚合查询实现方案
实现思路
- 首先使用
$unwind解构payments数组,将数组内的每个支付记录拆分为独立文档 - 借助
$facet聚合算子并行执行两条统计逻辑,避免多次扫描数据- 全局统计管道:统计原始文档总数、含税总金额、不含税总金额
- 支付方式统计管道:按支付方式分组求和对应交易金额
- 最后合并两条管道的输出结果,拼接为目标返回结构
完整聚合语句
db.collection.aggregate([ // 解构payments数组 { $unwind: "$payments" }, // 并行执行两类统计逻辑 { $facet: { // 全局统计管道 "globalStats": [ { $group: { _id: "$_id", // 按原文档ID分组去重,避免unwind导致的重复统计 totalTaxInclusive: { $first: "$totalTaxInclusive" }, totalTaxExclusive: { $first: "$totalTaxExclusive" } } }, { $group: { _id: null, totalCount: { $sum: 1 }, totalTaxInclusive: { $sum: "$totalTaxInclusive" }, totalTaxExclusive: { $sum: "$totalTaxExclusive" } } } ], // 支付方式分组统计管道 "paymentStats": [ { $group: { _id: "$payments.method", amount: { $sum: "$payments.amount" } } }, { $project: { _id: 0, method: "$_id", amount: 1 } } ] } }, // 提取全局统计结果 { $unwind: "$globalStats" }, // 拼接为目标返回结构 { $project: { _id: 0, totalCount: "$globalStats.totalCount", totalTaxInclusive: "$globalStats.totalTaxInclusive", totalTaxExclusive: "$globalStats.totalTaxExclusive", payments: "$paymentStats" } } ])
注意:如果存在
payments数组为空的文档,可将$unwind修改为$unwind: { path: "$payments", preserveNullAndEmptyArrays: true },避免这类文档被过滤,导致全局统计结果不准确。
内容的提问来源于stack exchange,提问作者Jeremy
相关产品推荐
相关产品推荐

