MongoDB 聚合 - 查找特定时间范围和日期内的文档 我有一个 MongoDB 集合,其中包含包含 ISODate 类型的 orderDate 字段的文档。我想查找 orderDate 在给定日期的特定小时范围内(例如 15:00:00 到 17:59:59)的文档数量。
输入:新日期(“2023-06-07T10:30:00Z”)从15:00:00到17:59:60
[
{
_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"
}
]
MongoDb 游乐场:https://mongoplayground.net/p/omFcFgufaBf
这里
$dateFromParts
我们可以使用:
db.collection.aggregate([
{
$match: {
$expr: {
$and: [
{
$gte: [
"$orderDate",
{
$dateFromParts: {
year: {
$year: new Date("2023-06-07T10:30:00Z")
},
month: {
$month: new Date("2023-06-07T10:30:00Z")
},
day: {
$dayOfMonth: new Date("2023-06-07T10:30:00Z")
},
hour: 15,
minute: 0,
second: 0,
millisecond: 0
}
}
]
},
{
$lte: [
"$orderDate",
{
$dateFromParts: {
year: {
$year: new Date("2023-06-07T10:30:00Z")
},
month: {
$month: new Date("2023-06-07T10:30:00Z")
},
day: {
$dayOfMonth: new Date("2023-06-07T10:30:00Z")
},
hour: 17,
minute: 59,
second: 60,
millisecond: 1000
}
}
]
}
]
}
}
}
])