我在一个集合中有以下文档:
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
推荐答案有关更有效的查询,请使用 $reduce 运算符以展平数组.这将允许您连接任意数量的数组,因此,不仅仅是将文档1和2中的两个数组进行并集,这也将适用于其他数组.
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的数组
发布评论