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

MongoDB查询近3个月数据失败问题求助

MongoDB查询近3个月数据(含跨年度场景)

问题分析

你遇到的核心问题是查询条件未正确生效,导致返回全部数据,具体原因如下:

  • 无效代码2的关键错误:将Date.getTime()返回的毫秒级时间戳除以1000转为秒级,但MongoDB中createdAt(由timestamps: true自动生成)的底层存储是毫秒级时间戳,秒级数值远小于所有数据的毫秒时间戳,因此$gte条件对所有数据都成立。
  • 无效代码1的潜在问题:setMonth()方法会修改原Date对象,同时返回毫秒时间戳,虽然Mongoose通常会自动转换类型,但这种写法易引发逻辑混乱,且你实际需求是3个月却写了减6个月的逻辑。

正确解决方案

直接生成3个月前的Date对象作为查询条件,MongoDB会自动处理跨年度的日期计算(比如从2024年1月倒推3个月,会自动得到2023年10月的日期):

简洁写法

const threeMonthsAgo = new Date();
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);

const invoices = await Invoice.find({
  createdAt: { $gte: threeMonthsAgo }
});

更严谨的写法(避免修改原Date对象)

如果需要保留当前时间的Date对象,可单独创建目标日期:

const now = new Date();
// 参数依次为:年、月、日,自动处理跨年度边界
const threeMonthsAgo = new Date(now.getFullYear(), now.getMonth() - 3, now.getDate());

const invoices = await Invoice.find({
  createdAt: { $gte: threeMonthsAgo }
});

验证说明

执行上述代码后,查询结果只会包含createdAt晚于3个月前的记录,完全支持跨年度场景(比如2023年11-12月 + 2024年1月的记录,当当前时间为2024年1月时)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:49:51