I’ve a schema something like this, where I got an array of startDate and endDate in the form of array of objects. Please find the screenshot below.
Now I need to check if current date is between any of the available dates range.
This is what I been trying,
db.products.aggregate([
{
"$match": {
"$and": [
{
"isDeleted": false
},
{
"isArchived": false
},
{
_id: ObjectId("63de4823561e0319a5745537")
},
{
bookings: {
'$elemMatch': {
$nin:[
{productBookingCompleteDate: { '$gt': new Date("2023-04-03T04:03:49.642Z") }},
{productBookingStartDate: { '$lt': new Date("2023-04-03T04:03:49.642Z") }}
]
}
}
}
]
}
},
...... // Rest of the logics
])
but this is returning data if current date is falling between these range, but I want the opposite case. It should return document only if the current date is not in any date range.
can anyone please help me with this.
Thanks.
>Solution :
To exclude a MongoDB document if the current date is between any dates available in an array of startDate and endDate objects, you can use the $elemMatch operator to check if there is any booking range that includes the current date. Then, you can negate the match using the $not operator to return only those documents where the current date is not within any booking range.
db.products.find({
_id: ObjectId("63de4823561e0319a5745537"),
isDeleted: false,
isArchived: false,
bookings: {
$not: {
$elemMatch: {
productBookingStartDate: { $lte: new Date() },
productBookingCompleteDate: { $gte: new Date() }
}
}
}
})
