将一个“对象数组"映射到一个简单的键值数组 [英] Map an 'array of objects' to a simple array of key values

查看:21
本文介绍了将一个“对象数组"映射到一个简单的键值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 mongoDB 聚合管道的新手,有一个非常基本的问题,但在任何地方都找不到答案.我想简单地转换以下块:

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"
            }
        ]

到:

"exclude" : [
            "Accenture",
            "Aon Consulting"
        ]

使用聚合管道,但即使在阅读了关于 https://docs.mongodb.com/manual/reference/operator/aggregation/.感谢您的帮助.

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.

推荐答案

在使用聚合框架来处理转换方面,您的方向肯定是正确的.将数组中的对象键映射到键值数组的主要运算符是 $map 在这种情况下.

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.

中一起使用它$addFields 用于投影转换字段的管道,如下所示:

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

<小时>

在上面的$addFields 管道阶段向文档添加新字段,如果新字段的名称与现有字段名称相同(包括 _id),$addFields 用指定表达式的值覆盖该字段的现有值.


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.

所以基本上上面使用 $map.$map 的工作原理是将表达式应用于输入数组的每个元素.该表达式使用 as 字段中指定的变量名称 ($$el) 单独引用每个元素,并返回一个包含应用结果的数组.

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.

这篇关于将一个“对象数组"映射到一个简单的键值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆