[英]MongoDB Aggregation - query collections that satisfies all array of objects not at least one
I have collections that have dates in an array like:我有 collections 的日期在数组中,例如:
datesArray: [{
start_date: Date,
end_date: Date
}]
I want only those collections which satisfy all elements of datesArray.我只想要那些满足 dateArray 的所有元素的 collections。
I am using it in aggregation $match operator like:我在聚合$match运算符中使用它,例如:
Model.aggregate([
{
$match: {
'datesArray.start_date': { $gte: new Date('11-01-21') },
'datesArray.end_date': { $lte: new Date('11-30-21') }
}
}
])
I tried with $elemMatch but it matches at least one array element.我尝试使用$elemMatch ,但它至少匹配一个数组元素。 I also tried $all with $elemMatch but had no success.我也用$elemMatch尝试了 $ all 但没有成功。
Thank you谢谢
$map
your datesArray
to a boolean array by your date range matching criteria. $map
your datesArray
按照您的日期范围匹配标准映射到 boolean 数组。 Perform $allElementsTrue
on the result to get your desired result.对结果执行$allElementsTrue
以获得您想要的结果。
inputDate1
and inputDate2
are your inputs. inputDate1
和inputDate2
是您的输入。 Feel free to update them.随时更新它们。
db.collection.aggregate([
{
"$addFields": {
"inputDate1": ISODate("2021-01-01"),
"inputDate2": ISODate("2021-12-31")
}
},
{
"$match": {
$expr: {
"$allElementsTrue": [
{
"$map": {
"input": "$datesArray",
"as": "d",
"in": {
$and: [
{
$gte: [
"$$d.start_date",
"$inputDate1"
]
},
{
$lte: [
"$$d.end_date",
"$inputDate2"
]
}
]
}
}
}
]
}
}
}
])
Here is the Mongo playground for your reference.这是Mongo游乐场供您参考。
You could simply invert each of the critera and use $nor
:您可以简单地反转每个标准并使用$nor
:
db.collection.aggregate([
{$match: {
$nor: [
{"datesArray.start_date": {$lt: ISODate("2021-11-01")}},
{"datesArray.end_date": {$gt: ISODate("2021-11-30")}}
]
}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.