MongoDB聚合:查找指定日期特定小时范围内的文档
MongoDB查询指定日期且时间在特定范围的文档
解决方案
方法1:直接构造时间范围(推荐,支持索引)
基于指定日期new Date("2023-06-07T10:30:00Z")构造当天的时间边界,通过范围匹配查询目标文档,这种方式能利用orderDate字段的索引,查询效率更高:
// 提取指定日期的UTC年月日,构造15:00到18:00的时间区间 const targetDate = new Date("2023-06-07T10:30:00Z"); const startRange = new Date(Date.UTC( targetDate.getUTCFullYear(), targetDate.getUTCMonth(), targetDate.getUTCDate(), 15, 0, 0 )); const endRange = new Date(Date.UTC( targetDate.getUTCFullYear(), targetDate.getUTCMonth(), targetDate.getUTCDate(), 18, 0, 0 )); // 执行查询 db.yourCollection.find({ orderDate: { $gte: startRange, $lt: endRange } })
方法2:用聚合操作符动态判断时间部分
如果需要灵活提取时分秒进行条件判断,可使用$expr结合日期操作符实现:
const targetDate = new Date("2023-06-07T10:30:00Z"); const targetYear = targetDate.getUTCFullYear(); const targetMonth = targetDate.getUTCMonth() + 1; // MongoDB的$month返回1-12,UTC月份为0-11 const targetDay = targetDate.getUTCDate(); db.yourCollection.find({ $expr: { $and: [ // 匹配指定日期的年月日 { $eq: [{ $year: "$orderDate" }, targetYear] }, { $eq: [{ $month: "$orderDate" }, targetMonth] }, { $eq: [{ $dayOfMonth: "$orderDate" }, targetDay] }, // 匹配15:00:00至17:59:59的时间范围 { $gte: [{ $hour: "$orderDate" }, 15] }, { $lt: [{ $hour: "$orderDate" }, 18] } ] } })
输入数据
[ { _id: 1, orderDate: ISODate("2023-06-07T10:30:00Z"), status: "Completed" }, { _id: 2, orderDate: ISODate("2023-06-07T17:00:00Z"), status: "Pending" }, { _id: 3, orderDate: ISODate("2023-06-07T20:15:00Z"), status: "Completed" }, { _id: 4, orderDate: ISODate("2023-06-08T09:00:00Z"), status: "Pending" }, { _id: 5, orderDate: ISODate("2023-06-08T14:30:00Z"), status: "Completed" } ]
预期输出
[ { "_id": 2, "orderDate": ISODate("2023-06-07T17:00:00Z"), "status": "Pending" } ]
内容的提问来源于stack exchange,提问作者mongoPioneer
相关产品推荐
相关产品推荐

