28

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.

2 Answers 2

30

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

Comments

22

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.

6 Comments

Thank you for the quick answer. It works like a charm! Your explanations are also very insightful. Cheers!
@RaenyvonHaus No worries, happy to help
Why do we use the double $ here "in": "$$el.name"?
@Morozov They are used to denote variables in aggregation expressions
How would one go about to make that list unique?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.