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.
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.
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.
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.
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' } } ])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With