Map an 'array of objects' to a simple array of key values

Raeny von Haus picture Raeny von Haus · Sep 28, 2017 · Viewed 13.3k times · Source

I am new to the mongoDB aggregation pipeline and have a really basic question but could not find the answer anywhere. I would like to simply convert the following block:

"exclude" : [
            {
                "name" : "Accenture"
            }, 
            {
                "name" : "Aon Consulting"
            }
        ]

to:

"exclude" : [
            "Accenture",
            "Aon Consulting"
        ]

using the aggregation pipeline but I cannot seem to find how to do it even after going through the documentation on https://docs.mongodb.com/manual/reference/operator/aggregation/. Thanks for your help.

Answer

AlexDenisov picture AlexDenisov · Sep 28, 2017

While @chridam's answer is correct, there is no need to use $map. Simple $addFields/$project would be sufficient:

db.collection.aggregate([
    {
        $addFields: {
            exclude : '$exclude.name'
        }
    }
])