MongoDB 查询每个文档对应子文档数组中日期最新记录的实现方法
MongoDB按根文档分组获取数组内最新日期记录方案
方案1:MongoDB 5.2+ 高性能方案(无需展开数组)
使用$sortArray直接对每个文档的Attributes数组内元素按日期降序排序后取首元素即可,查询语句如下:
db.collection.aggregate([ { $addFields: { sortedAttributes: { $sortArray: { input: "$Attributes", sortBy: { Date: -1 } } } } }, { $project: { _id: 0, Type: 1, Date: { $first: "$sortedAttributes.Date" }, Value: { $first: "$sortedAttributes.Value" } } } ])
方案2:低版本兼容方案
如果使用的是MongoDB 5.2之前的版本,可通过展开数组、排序、分组的方式实现:
db.collection.aggregate([ // 展开Attributes数组 { $unwind: "$Attributes" }, // 按Type分组,同组内按日期降序排序 { $sort: { Type: 1, "Attributes.Date": -1 } }, // 按Type分组,取每组第一条记录 { $group: { _id: "$Type", Date: { $first: "$Attributes.Date" }, Value: { $first: "$Attributes.Value" } } }, // 调整返回字段格式,和预期结果对齐 { $project: { _id: 0, Type: "$_id", Date: 1, Value: 1 } } ])
两种方案返回的结果都和给出的预期格式完全一致。
内容的提问来源于stack exchange,提问作者Irpie
相关产品推荐
相关产品推荐

