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

MongoDB查询history数组内指定时间段嵌套数据返回null如何解决

你的查询写法确实存在错误,问题出在嵌套数组字段的查询规则使用不当:
直接写history: { date: { $gte: ... } }的语法是要求history字段完全匹配你传入的对象结构,而非匹配数组内元素的date字段,因此永远找不到符合条件的文档返回null。

解决方案分两种场景实现:

场景1:匹配存在符合时间范围历史记录的完整文档

仅需要确认文档存在符合条件的历史记录,返回完整文档(包含所有history元素),使用点表示法查询嵌套数组字段即可:

Prices.findOne({
  collectibleId: slug,
  "history.date": {
    $gte: new Date("2021-10-26T00:00:00.000Z")
  }
}).exec((err, data) => {
  if (err){
    return res.status(400).json({
      error: errorHandler(err)
    })
  }
  res.json(data)
})

场景2:仅返回history数组中符合时间范围的元素

需要过滤掉history中不符合时间要求的条目,需要在查询的投影参数中使用$filter操作符处理数组:

Prices.findOne(
  // 第一个参数:查询匹配条件
  {
    collectibleId: slug,
    "history.date": { $gte: new Date("2021-10-26T00:00:00.000Z") }
  },
  // 第二个参数:投影配置,过滤返回的history字段
  {
    collectibleId: 1,
    createdAt: 1,
    updatedAt: 1,
    __v: 1,
    history: {
      $filter: {
        input: "$history",
        as: "historyItem",
        cond: { $gte: [ "$$historyItem.date", new Date("2021-10-26T00:00:00.000Z") ] }
      }
    }
  }
).exec((err, data) => {
  if (err){
    return res.status(400).json({
      error: errorHandler(err)
    })
  }
  res.json(data)
})

如果需要指定时间范围的上下限,修改cond的逻辑即可:

cond: {
  $and: [
    { $gte: [ "$$historyItem.date", new Date("2021-10-26T00:00:00.000Z") ] },
    { $lt: [ "$$historyItem.date", new Date("2021-10-28T00:00:00.000Z") ] }
  ]
}

内容的提问来源于stack exchange,提问作者alienbuild

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:54:07