MongoDB按machine_quality分组后匹配全局最大值的聚合查询问题
问题原因
你原有写法的核心问题是$match阶段是逐文档处理的,直接在$match里写$max: '$_id'只会取当前文档的_id值,无法拿到所有分组的全局最大值;同时$match中使用聚合运算需要用$expr包裹,否则语法不生效。
实现方案
方案1:MongoDB 5.0+ 极简写法(推荐)
用$setWindowFields窗口函数计算全局最大值,无需额外拆分合并分组:
db.records.aggregate([ { $group: { _id: '$machine_quality', total: { $sum: 1 } } }, // 计算全局最大machine_quality写入每个分组文档 { $setWindowFields: { partitionBy: null, output: { globalMaxQuality: { $max: '$_id', window: { documents: ['unbounded', 'unbounded'] } } } } }, // 按规则过滤 { $match: { $expr: { $gte: ['$_id', { $subtract: ['$globalMaxQuality', 3] }] } } }, // 可选:移除不需要的全局最大值字段 { $project: { globalMaxQuality: 0 } } ])
方案2:低版本兼容写法
如果你的MongoDB版本低于5.0不支持窗口函数,用$facet同时保留分组数据和计算全局最大值:
db.records.aggregate([ { $group: { _id: '$machine_quality', total: { $sum: 1 } } }, { $facet: { groupList: [], globalMax: [ { $group: { _id: null, maxVal: { $max: '$_id' } } } ] } }, { $set: { globalMaxQuality: { $first: '$globalMax.maxVal' } } }, { $unwind: '$groupList' }, { $replaceRoot: { newRoot: { $mergeObjects: ['$groupList', { globalMaxQuality: '$globalMaxQuality' }] } } }, { $match: { $expr: { $gte: ['$_id', { $subtract: ['$globalMaxQuality', 3] }] } } }, { $project: { globalMaxQuality: 0 } } ])
内容的提问来源于stack exchange,提问作者Fusion
相关产品推荐
相关产品推荐

