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

MongoDB聚合查询无法匹配数组首元素时间条件排查

问题原因及解决办法

核心问题:测试数据时间范围不匹配

你的查询逻辑本身没问题,但提供的测试文档中所有scores数组第一个元素的created_at都是2022年的,远早于当前时间的过去24小时范围,所以自然返回空结果。

验证查询逻辑的修正方式

把测试数据中的created_at改成接近当前时间的日期,比如:

[
  {
    "id": 1,
    "scores": [
      {
        "score": 1,
        "created_at": ISODate("2024-05-20T10:05:00.000+00:00")
      },
      {
        "score": 2,
        "created_at": ISODate("2022-11-20T00:05:00.000+00:00")
      }
    ]
  },
  {
    "id": 2,
    "scores": [
      {
        "score": 3,
        "created_at": ISODate("2024-05-20T11:05:00.000+00:00")
      },
      {
        "score": 5,
        "created_at": ISODate("2022-11-20T00:05:00.000+00:00")
      }
    ]
  }
]

再执行原查询就能得到符合条件的文档。

更健壮的查询写法

虽然$scores.0.created_at的写法合法,但用$arrayElemAt操作符获取数组第一个元素的写法更清晰,也能避免数组为空时的潜在问题,修改后的查询如下:

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $gte: [
          { $arrayElemAt: ["$scores.created_at", 0] },
          { $subtract: ["$$NOW", 86400000] }
        ]
      }
    }
  }
])

内容的提问来源于stack exchange,提问作者John M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:05:32