简体   繁体   中英

Mongodb - Retrieve select value from array of objects

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?

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"
        }
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM