[英]MongoDB Aggregation - Merge arrays of an object
I would like to get the union of all the arrays in an object in MongoDB 3.4 using the aggregation framework: 我想使用聚合框架在MongoDB 3.4中获取对象中所有数组的并集:
This is the input: 这是输入:
{
_id: "001",
name: "something",
important_part: {
foo: [1,2,3],
bar: [4,5],
x: [6,7]
}
}
This should be the output: 这应该是输出:
{
_id: "001",
name: "something",
merged_arrays: [1,2,3,4,5,6,7]
}
The tricky part is, that the fields in the important_part object is dynamic, and I don't think the $setUnion operator can be used, as it needs the exact list of array fields. 最棘手的部分是,在important_part对象中的字段是动态的,而且我不认为$ setUnion运营商都可以使用,因为它需要阵列方面的准确名单。
Could someone please help me? 有人可以帮我吗?
Thx in advance 提前Thx
You can use below aggregation in 3.4. 您可以在3.4中使用以下汇总。
$objectToArray
to transform object into array of key value pairs and $reduce
to $concatArrays
. $objectToArray
将对象转换为键值对数组,并将$reduce
为$concatArrays
。
db.col.aggregate({
"$addFields":{
"merged_arrays":{
"$reduce":{
"input":{"$objectToArray":"$important_part"},
"initialValue":[],
"in":{"$concatArrays":["$$value", "$$this.v"]}
}
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.