$ setUnion合并来自多个文档MongoDB的数组 [英] $setUnion to merge array from multiple documents MongoDB
问题描述
我在一个集合中有以下文档:
I have documents in a collection as follows :
{ _id : 1 , data : [7,4,0] }
{ _id : 2 , data : [4,5,6] }
{ _id : 3 , data : [6,7,8] }
我想合并两个或更多文档中的data
数组.
I want to union the data
array from two or more documents.
我用来查找id
1和2的data
数组的并集的查询是:
The query I am using to find the union of data
array of id
1 and 2 is:
db.coll.aggregate(
{
$match : {
_id: { $in: [1, 2] }
}
},
{
$group: {
_id: 0,
s0: { $first: "$data"},
s1: { $first: "$data"}
}
},
{
$project: {
_id: 0,
ans: { $setUnion: [ "$s0","$s1"]}
}
}
).pretty()
但查询结果为:
{7, 5, 0}
似乎仅是id
1的数据.
如何在同一阵列上的两个或多个文档之间实现联合 场?
How to achieve the union between two or more documents on same array field?
PS:我正在使用MongoDB 3.4
推荐答案
For a more efficient query, use the $reduce
operator to flatten the arrays. This will allow you to concat any number of arrays, so instead of just doing a union of the two arrays from docs 1 and 2, this will also apply for other arrays as well.
考虑运行以下聚合操作:
Consider running the following aggregate operation:
db.coll.aggregate([
{ "$match": { "_id": { "$in": [1, 2] } } },
{
"$group": {
"_id": 0,
"data": { "$push": "$data" }
}
},
{
"$project": {
"data": {
"$reduce": {
"input": "$data",
"initialValue": [],
"in": { "$setUnion": ["$$value", "$$this"] }
}
}
}
}
])
示例输出
{
"_id" : 0,
"data" : [ 0, 4, 5, 6, 7 ]
}
这篇关于$ setUnion合并来自多个文档MongoDB的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!