I am stuck in element match in array condition,
Sample Documents:
[
{
"_id": 1,
"rooms": [
{ date: ISODate("2021-02-25T00:00:00.000Z"), status: true, otherfield: true },
{ date: ISODate("2021-02-26T00:00:00.000Z"), status: true, otherfield: true },
{ date: ISODate("2021-02-27T00:00:00.000Z"), status: true, otherfield: true },
// there will be same date's document in rooms array like below row is similar to first row
{ date: ISODate("2021-02-25T00:00:00.000Z"), status: true, otherfield: true }
]
},
{
"_id": 2,
"rooms": [
{ date: ISODate("2021-02-25T00:00:00.000Z"), status: true, otherfield: true },
{ date: ISODate("2021-02-26T00:00:00.000Z"), status: false, otherfield: true },
{ date: ISODate("2021-02-27T00:00:00.000Z"), status: true, otherfield: true }
]
},
{
"_id": 3,
"rooms": [
{ date: ISODate("2021-02-25T00:00:00.000Z"), status: true, otherfield: true }
]
}
]
Condition criteria:
- rooms array should have 2 dates
2021-02-25T00:00:00.000Z
&2021-02-26T00:00:00.000Z
and both should have status true
as per condition it should select first document see below screenshot,
1) Try: - this selecting 2 documents because $in
means OR condition in date field, and $all
will not work because date inside $elemMatch
is a single sting,
db.collection.find({
rooms: {
$elemMatch: {
date: {
$in: [
ISODate("2021-02-25T00:00:00.000Z"),
ISODate("2021-02-26T00:00:00.000Z")
]
},
status: true
}
}
})
2) Try: - this selecting 2 documents because both condition will match in different elements of rooms,
db.collection.find({
"rooms.date": {
$all: [
ISODate("2021-02-25T00:00:00.000Z"),
ISODate("2021-02-26T00:00:00.000Z")
]
},
rooms: { $elemMatch: { status: true } }
})
Please suggest any possible way, thank you.