MongoDB 4.2 聚合分组取最大日期时如何获取对应非分组Value字段
方案1:MongoDB 5.2及以上版本(推荐)
直接用$top聚合运算符,分组时直接按日期倒序取每组第一条的所有需要的字段,性能最优,不需要额外的排序阶段,分组阶段直接完成所有计算:
db.direct_client.aggregate([ { $group: { _id: "$name", count: { $sum: 1 }, max_date_item: { $top: { sortBy: { created_date: -1 }, output: { created_date: "$created_date", value: "$value", city: "$city" } } } } }, // 可选:把字段平铺开,和原有输出格式对齐 { $project: { _id: 0, name: "$_id", count: 1, max_date: "$max_date_item.created_date", max_date_value: "$max_date_item.value", max_date_city: "$max_date_item.city" } } ])
方案2:兼容所有MongoDB版本的通用方案
先按name和created_date倒序排序,再分组时用$first取排序后的第一条对应字段即可:
db.direct_client.aggregate([ // 先按name分组、再按日期倒序排列,保证每个name下最新的记录排在最前面 { $sort: { name: 1, created_date: -1 } }, { $group: { _id: "$name", count: { $sum: 1 }, max_date: { $first: "$created_date" }, max_date_value: { $first: "$value" }, max_date_city: { $first: "$city" } } }, // 可选:调整输出字段格式 { $project: { _id: 0, name: "$_id", count: 1, max_date: 1, max_date_value: 1, max_date_city: 1 } } ])
如果数据量较大,建议提前给{name:1, created_date:-1}建复合索引,能大幅提升排序阶段的性能。
内容的提问来源于stack exchange,提问作者Alan Mil
相关产品推荐
相关产品推荐

