i have a database structured like this:
You need to $unwind the first array then you can easily apply $filter on the nested array
db.collection.aggregate([
{ "$unwind": "$Hospitais" },
{ "$match": { "Hospitais.nome": "Dorio Silva" } },
{ "$project": {
"Hospitais": {
"$filter": {
"input": "$Hospitais.utis",
"as": "uti",
"cond": {
"$eq": ["$$uti.nome", "UTI1"]
}
}
}
}}
])
Or you can try this as well
db.collection.aggregate([
{ "$match": { "Hospitais.nome": "Dorio Silva" } },
{ "$project": {
"Hospitais": {
"$filter": {
"input": {
"$map": {
"input": "$Hospitais",
"as": "hospital",
"in": {
"nome": "$$hospital.nome",
"utis": {
"$filter": {
"input": "$$hospital.utis",
"as": "uti",
"cond": {
"$eq": ["$$uti.nome", "UTI1"]
}
}
}
}
}
},
"as": "hospital",
"cond": {
"$eq": ["$$hospital.nome", "Dorio Silva"]
}
}
}
}}
])
Both will give the similar output
[
{
"Hospitais": [
{
"_id": 893910,
"leitos": [
{
"_id": 1.2893812e+08,
"_paciente": "Oliver"
},
{
"_id": 1.2803918239e+10,
"_paciente": "Priscilla"
}
],
"nome": "UTI1"
}
]
}
]