基于当前日期区间的MongoDB/Mongoose Recharge_Date过滤查询方案
针对Mongoose按日期区间查询Recharge_Date的解决方案
需求梳理
根据当前日期所属的当月区间(1-10日、11-20日),查询Recharge_Date(ISODate类型)落在对应区间的记录,核心是通过日期范围比较实现过滤。
实现步骤与代码
1. 计算目标日期区间
首先根据当前日期判断所属区间,生成对应的起始和结束日期:
- 若当前日在1-10日:查询当月1日00:00 至 当月11日00:00的记录(用
$lt11日确保包含10日23:59:59的所有数据) - 若当前日在11-20日:查询当月11日00:00 至 当月21日00:00的记录
2. 原生Date对象实现
无需额外依赖,用JS原生Date处理:
const now = new Date(); const currentYear = now.getFullYear(); const currentMonth = now.getMonth(); // 注意:月份是0-11(如6月对应5) let startDate, endDate; const currentDay = now.getDate(); if (currentDay >= 1 && currentDay <= 10) { startDate = new Date(currentYear, currentMonth, 1); endDate = new Date(currentYear, currentMonth, 11); } else if (currentDay >= 11 && currentDay <= 20) { startDate = new Date(currentYear, currentMonth, 11); endDate = new Date(currentYear, currentMonth, 21); } // 执行Mongoose查询 const targetRecords = await YourRechargeModel.find({ Recharge_Date: { $gte: startDate, $lt: endDate } });
3. Moment.js简化实现
如果项目中已使用Moment.js,代码更简洁易读:
const moment = require('moment'); const now = moment(); let startDate, endDate; const currentDay = now.date(); if (currentDay <= 10) { startDate = now.startOf('month').toDate(); endDate = now.date(11).startOf('day').toDate(); } else if (currentDay <= 20) { startDate = now.date(11).startOf('day').toDate(); endDate = now.date(21).startOf('day').toDate(); } // 执行查询 const targetRecords = await YourRechargeModel.find({ Recharge_Date: { $gte: startDate, $lt: endDate } });
关键细节
- 使用
$lt而非$lte:避免误包含结束日期的00:00:00时刻,确保区间范围准确覆盖到目标日期的最后一秒。 - 跨月场景扩展:如果业务需要当前在1-10日时查询上月21日至当月10日,只需调整
startDate为new Date(currentYear, currentMonth - 1, 21)即可。
内容的提问来源于stack exchange,提问作者Atul Kumar
相关产品推荐
相关产品推荐

