I have the following data:
const Availabilities = new Schema({
id: Number,
reservations: [{ from: Date, to: Date }]
});
const Availability = mongoose.model('Availability', Availabilities);
Basically i want to get a list of products in which the dates do not overlap with the query
[
{
id: 1,
reservations: [
{
from: '2022-01-01',
to: '2022-03-31',
},
{
from: '2022-04-01',
to: '2022-06-01',
},
],
},
{
id: 2,
reservations: [
{
from: '2022-01-01',
to: '2022-12-31',
},
],
},
{
id: 3,
reservations: [
{
from: '2022-02-01',
to: '2022-06-30',
},
],
},
]
and I want to filter all those who are not in a specific range. Example:
query = { from: "2022-07-01", to: "2022-08-31" }
should return
[
{
id: 1,
reservations: [
{
from: '2022-01-01',
to: '2022-03-31',
},
{
from: '2022-04-01',
to: '2022-06-01',
},
],
},
{
id: 3,
reservations: [
{
from: '2022-02-01',
to: '2022-06-30',
},
],
},
]
You can just check if one of two conditions are met, either:
to is smaller than the start of your input ( meaning the session ended before )from is bigger than the end of your input ( meaning the session started after )This is how it'll look in code:
db.collection.aggregate([
{
$match: {
reservations: {
$elemMatch: {
$or: [
{
to: {
$lt: "2022-07-01"
},
},
{
from: {
$gt: "2022-08-31"
}
}
]
}
}
}
},
{
$addFields: {
reservations: {
$filter: {
input: "$reservations",
cond: {
$or: [
{
$lt: [
"$$this.to",
"2022-07-01"
]
},
{
$gt: [
"$$this.to",
"2022-08-31"
]
}
]
}
}
}
}
}
])