Anda perlu $unwind
array pertama maka Anda dapat dengan mudah menerapkan $filter
pada larik bersarang
db.collection.aggregate([
{ "$unwind": "$Hospitais" },
{ "$match": { "Hospitais.nome": "Dorio Silva" } },
{ "$project": {
"Hospitais": {
"$filter": {
"input": "$Hospitais.utis",
"as": "uti",
"cond": {
"$eq": ["$$uti.nome", "UTI1"]
}
}
}
}}
])
Atau Anda dapat mencoba ini juga
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"]
}
}
}
}}
])
Keduanya akan memberikan output yang serupa
[
{
"Hospitais": [
{
"_id": 893910,
"leitos": [
{
"_id": 1.2893812e+08,
"_paciente": "Oliver"
},
{
"_id": 1.2803918239e+10,
"_paciente": "Priscilla"
}
],
"nome": "UTI1"
}
]
}
]