Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 794
Raeny von Haus Avatar asked Sep 28 '17 10:09

Raeny von Haus


People also ask

How do you map an array to an array of objects?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.

How do you turn an array of objects into a map?

To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.

How do you access keys in an array of objects?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.


1 Answers

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'         }     } ]) 
like image 85
AlexDenisov Avatar answered Sep 17 '22 17:09

AlexDenisov