如何使用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
相关产品推荐
相关产品推荐

