Vyzkoušejte následující agregační kanál, nevrací prázdné pole pro neaktivní prvky, ale je blíže výsledku:
db.collection.aggregate([
{
"$match": {
"name": "Andre",
"$or": [
{ "fruits.active": true },
{ "cars.active": true }
]
}
},
{ "$unwind": "$fruits" },
{ "$unwind": "$cars" },
{
"$match": {
"$or": [
{ "fruits.active": true },
{ "cars.active": true }
]
}
},
{
"$project": {
"name": 1,
"active_cars": "$cars.active",
"active_fruits": "$fruits.active",
"cars": 1,
"fruits": 1
}
},
{
"$project": {
"name": 1,
"cars": {
"$cond": [
{ "$eq": ["$active_cars", true] },
"$cars",
{}
]
},
"fruits": {
"$cond": [
{ "$eq": ["$active_fruits", true] },
"$fruits",
{}
]
}
}
},
{
"$group": {
"_id": {
"_id": "$_id",
"name": "$name"
},
"cars": { "$addToSet" : "$cars" },
"fruits": { "$addToSet" : "$fruits" }
}
},
{
"$project": {
"_id": 0,
"name": "$_id.name",
"cars": 1,
"fruits": 1
}
}
])
Výstup
/* 1 */
{
"result" : [
{
"cars" : [
{
"active" : true,
"carname" : "GM"
}
],
"fruits" : [{}],
"name" : "Andre"
}
],
"ok" : 1
}