I've got a collection were documents have nested arrays, and I would like to select only the lower arrays, is it possible?
I have tried this but it doesn't work:
db.collection.find({},{'family.children.$.toys' :1})
document example
{
"id":1000,
"name": "Bob",
"surname":"The Builder",
"family":{
"size":2,
"status": "happy",
"children":[{
"name":"Jim",
"school": "St. Mary",
"toys":[{
"name":"Lego"
},
{
"name":"Playstation"
}]
},
{
"name":"Kate",
"school": "St. Mary",
"toys":[{
"name":"Xbox"
},
{
"name":"Barbie"
}]
}
]
}
}
Expected result (extract only toys list):
{
_id:1000,
family:{
childrens:[{
toys:[{
name:Lego
},
{
name:Playstation
}]
},
{
toys:[{
name:Xbox,
},
{
name:Barbie
}]
}
]
}}
db.collection.find({},{'id':1, 'family.children.toys' :1, '_id':0})
Sample output:
{
"id" : 1000,
"family" : {
"children" : [
{
"toys" : [
{
"name" : "Lego"
},
{
"name" : "Playstation"
}
]
},
{
"toys" : [
{
"name" : "Xbox"
},
{
"name" : "Barbie"
}
]
}
]
}
}
You can also do this with aggregation. You use the $map
operator to return only the toys
field.
db.collection.aggregate([{
"$project": {
"family.childrens": {
"$map": {
"input": "$family.children",
"as": "f",
"in": { "toys": "$$f.toys" }
}
}
}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With