MongoDB聚合查询中countTransfer统计值错误问题求助
解决MongoDB聚合中transfer非空origin/destiny统计错误的问题
核心问题是你不需要通过$unwind处理transfer数组来统计目标字段,直接在$group阶段用条件判断就能精准计算,还不会影响其他统计项。
修改方案
在$group阶段里,针对countTransferWithNonEmptyOriginDestiny字段,用$sum结合$cond直接判断文档是否满足:
transfer对象存在(不为null)transfer.origin非空字符串transfer.destiny非空字符串
替换后的关键代码片段:
{ $group: { _id: null, // 其他统计项保持不变... countTransferWithNonEmptyOriginDestiny: { $sum: { $cond: [ { $and: [ { $ne: ["$transfer", null] }, { $ne: ["$transfer.origin", ""] }, { $ne: ["$transfer.destiny", ""] } ] }, 1, 0 ] } } } }
为什么原来的方法不行?
- 用
$unwind处理transfer数组时,不管preserveNullAndEmptyArrays设为true还是false,都会改变文档结构:要么保留空值导致统计错误,要么过滤掉空值影响其他依赖原文档的统计项。 - 直接在
$group里做条件判断,是基于原始文档的属性进行统计,不会破坏原有数据结构,其他统计项完全不受影响。
内容的提问来源于stack exchange,提问作者knoppix
相关产品推荐
相关产品推荐

