如何在Mongoose中查询指定日期(忽略时间)的记录?
解决MongoDB按日期忽略时间查询的问题
你遇到的核心问题是:数据库里的logDate是带UTC时分秒的完整时间,而你用$lte: ISODate('2023-09-12')时,这个日期对应的是UTC时间2023-09-12 00:00:00,但你数据库里的2023-09-12记录都是00:10之后的,甚至到23:34,这些时间都比00:00大,所以自然查不到。
正确的做法是把查询范围设为:目标日期的0点(UTC)开始,到下一天的0点(UTC)结束,用$gte匹配开始时间,$lt匹配结束时间,这样就能覆盖目标日期的所有时间记录。
1. MongoDB Compass 直接查询示例
把你的查询语句改成这样:
{ employeeId: ObjectId('64f9731b4f8f4f269a44e7af'), logDate: { $gte: ISODate('2023-09-12T00:00:00.000Z'), $lt: ISODate('2023-09-13T00:00:00.000Z') } }
2. Mongoose 代码修改
不管你用原生Date还是moment,核心都是生成目标日期的起始UTC时间和下一天的起始UTC时间:
用原生Date对象处理
const findActivityLogsByFilter = async (filter: TEmployeeFilter, currentUser: IEmployeeAttributes) => { try { // 处理日期:把startDate转为当天UTC0点,endDate转为下一天UTC0点 const startDate = new Date(filter.startDate); startDate.setUTCHours(0, 0, 0, 0); const endDate = new Date(filter.endDate); endDate.setUTCHours(0, 0, 0, 0); endDate.setUTCDate(endDate.getUTCDate() + 1); return await employee_activity_logsModel .find({ employeeId: filter.employeeId, activity: { $in: filter.actions }, logDate: { $gte: startDate, $lt: endDate }, // 这里用$lt而不是$lte _discontinuedUser: null, }) .sort({ _id: 'desc' }) .exec(); } catch (error) { throw new InternalServerError(messages.generalMessage.Error); } };
用moment库处理
如果你习惯用moment,代码可以更简洁:
const findActivityLogsByFilter = async (filter: TEmployeeFilter, currentUser: IEmployeeAttributes) => { try { const startDate = moment(filter.startDate).utc().startOf('day').toDate(); // 直接取目标日期下一天的UTC0点作为结束边界 const endDate = moment(filter.endDate).utc().startOf('day').add(1, 'day').toDate(); return await employee_activity_logsModel .find({ employeeId: filter.employeeId, activity: { $in: filter.actions }, logDate: { $gte: startDate, $lt: endDate }, _discontinuedUser: null, }) .sort({ _id: 'desc' }) .exec(); } catch (error) { throw new InternalServerError(messages.generalMessage.Error); } };
关键注意点
- 一定要统一用UTC时间处理,避免时区差异导致的查询错误(比如你本地是台北时间,转UTC时要确保日期计算正确)
- 用
$lt下一天的0点,而不是$lte当天的23:59:59.999,后者可能会漏掉极个别毫秒级的记录,前者更稳妥
内容的提问来源于stack exchange,提问作者Raymond
相关产品推荐
相关产品推荐

