问题描述
我是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.
这篇关于将“对象数组"映射到简单的键值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!