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

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


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


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.