Raeny von Haus
Raeny von Haus

Reputation: 394

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

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.

Upvotes: 28

Views: 19502

Answers (2)

AlexDenisov
AlexDenisov

Reputation: 4117

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'
        }
    }
])

Upvotes: 30

chridam
chridam

Reputation: 103375

You certainly were in the right direction in using the aggregation framework to handle the transformation. The main operator that maps the object keys in the array to an array of the key values only would be $map in this case.

Use it together within a $addFields pipeline to project the transformed field as follows:

db.collection.aggregate([
    {
        "$addFields": {
            "exclude": {
                "$map": {
                    "input": "$exclude",
                    "as": "el",
                    "in": "$$el.name"
                }
            }
        }
    }
])

In the above, the $addFields pipeline stage adds new fields to documents and if the name of the new field is the same as an existing field name (including _id), $addFields overwrites the existing value of that field with the value of the specified expression.

So essentially the above replaces the excludes array with the transformed array using $map. $map works by applying an expression to each element of the input array. The expression references each element individually with the variable name ($$el) specified in the as field and returns an array with the applied results.

Upvotes: 22

Related Questions