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

你说的曾经没有我的故事 提交于 2019-12-17 19:49:24

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/46466409/map-an-array-of-objects-to-a-simple-array-of-key-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!