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

如何使用Mongoose查询MongoDB中上个月的自然月数据?

Mongoose 查询MongoDB中上个月完整月份的数据

你的问题出在没有精准定位上个月的完整日期范围——原来的代码只是把当前日期减了一个月,得到的是「过去30天左右」的区间,而不是上个月的整月数据。

要获取上个月的所有数据,你需要明确两个时间点:

  • 上个月的第一天00:00:00
  • 当前月份的第一天00:00:00

查询时只需要匹配createdAt大于等于上个月第一天,且小于当前月份第一天的文档(用$lt而非$lte,避免误包含当月第一天的0点数据)。

完整实现代码

const now = new Date();
// 获取当前年份和月份
const currentYear = now.getFullYear();
const currentMonth = now.getMonth();

// 计算上个月的年份和月份(处理跨年情况,比如1月对应去年12月)
const lastMonthYear = currentMonth === 0 ? currentYear - 1 : currentYear;
const lastMonth = currentMonth === 0 ? 11 : currentMonth - 1;

// 构造上个月第一天0点和当月第一天0点的时间对象
const startOfLastMonth = new Date(lastMonthYear, lastMonth, 1, 0, 0, 0);
const startOfCurrentMonth = new Date(currentYear, currentMonth, 1, 0, 0, 0);

// 执行Mongoose查询
const income = await this.incomeModel.find({
  createdAt: {
    $gte: startOfLastMonth,
    $lt: startOfCurrentMonth
  }
});

逻辑验证

以你提供的文档为例:

  • 如果当前是11月,startOfLastMonth为2022-10-01 00:00:00,startOfCurrentMonth为2022-11-01 00:00:00
  • 第一个文档的createdAt是2022年10月20日,完全落在区间内会被匹配;第二个文档是2022年11月3日,超出区间会被排除,完全符合你的需求。

这种写法还能自动处理跨年场景:比如当前是1月时,会自动定位到去年的12月,不会出现日期计算错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:33:49