[英]How to find documents that their data match a condition on at least one item from a given array of items - mongoDB
我想獲取提供的日期數組中存在的記錄。
這個提供的日期數組將獲取開始和結束日期之間的記錄。
例子:
我有這個架構:
[
{
"_id": "1",
"course": "Maths",
"startDate": "2022-06-07",
"endDate": "2022-06-12"
},
{
"_id": "2",
"course": "Chemistry",
"startDate": "2022-06-06",
"endDate": "2022-06-09"
},
{
"_id": "3",
"course": "Physics",
"startDate": "2022-06-08",
"endDate": "2022-06-10"
},
{
"_id": "4",
"course": "Computer Science",
"startDate": "2022-06-10",
"endDate": "2022-06-18"
},
{
"_id": "5",
"course": "Computer Science",
"startDate": "2022-06-10",
"endDate": "2022-06-13"
},
{
"_id": "6",
"course": "Biology",
"startDate": "2022-06-08",
"endDate": "2022-06-10"
}
]
提供數組:
["2022-06-06", "2022-06-17"]
預期的響應是:
[
{
"_id": "2",
"course": "Chemistry",
"startDate": "2022-06-06",
"endDate": "2022-06-09"
},
{
"_id": "4",
"course": "Computer Science",
"startDate": "2022-06-10",
"endDate": "2022-06-18"
}
]
誰能幫我查詢? 謝謝
您可以將聚合管道與$filter
一起使用:
matchingDates
字段,該字段對dates
數組中與條件匹配的項目進行計數。$match
僅具有此類項目的文檔。db.collection.aggregate([
{$addFields: {dates: ["2022-06-06", "2022-06-17"]}},
{
$set: {
matchingDates: {
$size: {
$filter: {
input: "$dates",
as: "item",
cond: {
$and: [
{$gte: [{$toDate: "$$item"}, {$toDate: "$startDate"}]},
{$lte: [{$toDate: "$$item"}, {$toDate: "$endDate"}]}
]
}
}
}
}
}
},
{$match: {matchingDates: {$gt: 0}}},
{$unset: ["dates", "matchingDates"]}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.