1

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?

2
  • Is item root key of the document? Commented Feb 3, 2016 at 16:17
  • Yes. { items : [ .. ] } - i just edited the question to make it more clear. Commented Feb 3, 2016 at 16:23

1 Answer 1

2

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"
        }
    ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

That makes sense. Is there a more dynamic dynamic solution? If an item had a child in a child in a child, I would need to write items.children.children.children.name. Do you think there is a way to just say: 'never display color'?
No there is no direct way to do the same. Then you will have to iterate on each document and do the operations on each document.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.