I need to filter a multi-level nested array in MongoDB. The schema is as follows,
{
"_id": "1234",
"array1": [
{
"id": "a11",
"array2": [
{
"id": "a21",
"array3": [
{
"id": "a31",
"status": "done"
},
{
"id": "a32",
"status": "pending"
}
]
}
]
}
]
}
The required output must filter array3 with condition status=done. Which is the best possible method to achieve the same?
3
Answers
Use
$map
to iteratearray1
andarray2
, use$filter
to filterarray3
. Finally comparearray3
with empty array for document matching.Here is the Mongo playground for your reference.
Query
$mergeObjects
allows us to not write the fields by hand($setField can be used also if mongoDB5+) (if instead of id you also have 10 fields, this will work without changing the query)Playmongo
i just asnwered the same question from https://stackoverflow.com/a/75599962/9267467
the query is simply.
let me put my code here again because this is more deeper
MONGO PLAYGROUND