Reputation: 202
I have an array containing objects.
These objects have a name and a color. Some objects can also contain children! (an array of other objects).
{
items : [
{
name: 'box'
color: 'red'
},
{
name: 'circle'
color: 'blue'
children: [
{
name: 'sphere'
color: 'orange'
},
{
name: 'polygons'
color: 'green'
}
]
},
{
name: 'triangle'
color: 'pink'
}
]
}
I need to retrieve all the names of these items and exclude their colors.
The result should be:
items : [
{
name: 'box'
},
{
name: 'circle'
children: [
{
name: 'sphere'
},
{
name: 'polygons'
}
]
},
{
name: 'triangle'
}
]
I have looked at aggregation extensively but can't seem to find a solution!
How can I exclude a value from being retrieved in an array of objects?
Upvotes: 1
Views: 814
Reputation: 3125
No need of aggregation.
db.coll.find({}, {'_id' : 0, 'items.name' : 1, 'items.children.name' : 1})
Will give the following output
{
"items" : [
{
"name" : "box"
},
{
"name" : "circle",
"children" : [
{
"name" : "sphere"
},
{
"name" : "polygons"
}
]
},
{
"name" : "triangle"
}
]
}
Upvotes: 2