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

如何在MongoDB中按年份及特定年月筛选数据?

MongoDB按年份/年月筛选日期数据的正确方法

一、按年份筛选数据(解决$gte/$lte返回空的问题)

你用$gte/$lte返回空结果,大概率是日期参数格式错误或者边界值设置不对。createdAt是Date类型,必须用合法的Date对象匹配,不能直接传数字年份。

正确写法(利用索引,性能最优)

要筛选某一年的数据,需指定该年份的起始时间(1月1日0点)和下一年的起始时间(用$lt而非$lte,避免包含下一年的第一条数据):

// 筛选2022年的数据
db.yourCollectionName.find({
  createdAt: {
    $gte: new Date('2022-01-01T00:00:00.000Z'),
    $lt: new Date('2023-01-01T00:00:00.000Z')
  }
})

// 筛选2023年的数据
db.yourCollectionName.find({
  createdAt: {
    $gte: new Date('2023-01-01T00:00:00.000Z'),
    $lt: new Date('2024-01-01T00:00:00.000Z')
  }
})

替代写法(聚合管道,无需构造日期边界)

如果不想手动计算日期边界,也可以用聚合管道的$year操作符匹配年份,但这种方法无法利用createdAt字段的索引,数据量大时性能会下降:

// 筛选2022年的数据
db.yourCollectionName.aggregate([
  {
    $match: {
      $expr: { $eq: [{ $year: "$createdAt" }, 2022] }
    }
  }
])

二、按特定年份和月份筛选数据

比如筛选2023年11月的数据,同样用日期边界的方法最靠谱:

最优写法(支持索引)

// 筛选2023年11月的数据
db.yourCollectionName.find({
  createdAt: {
    $gte: new Date('2023-11-01T00:00:00.000Z'),
    $lt: new Date('2023-12-01T00:00:00.000Z')
  }
})

聚合管道写法

db.yourCollectionName.aggregate([
  {
    $match: {
      $expr: {
        $and: [
          { $eq: [{ $year: "$createdAt" }, 2023] },
          { $eq: [{ $month: "$createdAt" }, 11] } // 月份为1-12的数字
        ]
      }
    }
  }
])

验证你的示例数据

用2022年筛选语句,会返回以下两条数据:

{
    _id: new ObjectId("63ac23b357dc96"),
    details: 'hi i am feeling good today',
    status: '1',
    createdAt: 2022-12-28T11:08:40.400Z,
},
{
    _id: new ObjectId("63b2b2afa0d8e"),
    details: 'Hello!! This is Ankit and feeling good',
    status: '1',
    createdAt: 2022-11-14T10:31:36.098Z
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:15:27