You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 04:45:06