MongoDB聚合运算符:$setUnion
$setUnion
聚合运算符返回两个或多个数组的并集。
语法
{ $setUnion: [ <expression1>, <expression2>, ... ] }
<expression>
为可解析为数组的表达式。
使用
$setUnion
对数组执行集合操作,将数组视为集合。如果数组包含重复元素,$setUnion
会忽略重复元素,并且$setUnion
也会忽略元素的顺序。
如果集合包含嵌套数组元素,$setUnion
不会进入嵌套数组,而对顶层对数组进行评估。
举例 | 结果 |
---|---|
{ $setUnion: [ [ "a", "b", "a" ], [ "b", "a" ] ] } | [ "b", "a" ] |
{ $setUnion: [ [ "a", "b" ], [ [ "a", "b" ] ] ] } | [ [ "a", "b" ], "b", "a" ] |
举例
使用下面的脚本创建flowers
集合:
db.flowers.insertMany( [
{ "_id" : 1, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid" ] },
{ "_id" : 2, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "orchid", "rose", "orchid" ] },
{ "_id" : 3, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid", "jasmine" ] },
{ "_id" : 4, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "jasmine", "rose" ] },
{ "_id" : 5, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ ] },
{ "_id" : 6, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose" ], [ "orchid" ] ] },
{ "_id" : 7, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose", "orchid" ] ] },
{ "_id" : 8, "flowerFieldA" : [ ], "flowerFieldB" : [ ] },
{ "_id" : 9, "flowerFieldA" : [ ], "flowerFieldB" : [ "rose" ] }
] )
下面的操作使用$setUnion
运算符返回在数组flowerFieldA
或数组flowerFieldB
中出现的元素的数组,就是两个数组的并集:
db.flowers.aggregate(
[
{ $project: { flowerFieldA:1, flowerFieldB: 1, allValues: { $setUnion: [ "$flowerFieldA", "$flowerFieldB" ] }, _id: 0 } }
]
)
操作返回下面的结果:
{ "flowerFieldA": [ "rose", "orchid" ], "flowerFieldB": [ "rose", "orchid" ], "allValues": [ "orchid", "rose" ] }
{ "flowerFieldA": [ "rose", "orchid" ], "flowerFieldB": [ "orchid", "rose", "orchid" ], "allValues": [ "orchid", "rose" ] }
{ "flowerFieldA": [ "rose", "orchid" ], "flowerFieldB": [ "rose", "orchid", "jasmine" ], "allValues": [ "orchid", "rose", "jasmine" ] }
{ "flowerFieldA": [ "rose", "orchid" ], "flowerFieldB": [ "jasmine", "rose" ], "allValues": [ "orchid", "rose", "jasmine" ] }
{ "flowerFieldA": [ "rose", "orchid" ], "flowerFieldB": [ ], "allValues": [ "orchid", "rose" ] }
{ "flowerFieldA": [ "rose", "orchid" ], "flowerFieldB": [ [ "rose" ], [ "orchid" ] ], "allValues": [ "orchid", "rose", [ "rose" ], [ "orchid" ] ] }
{ "flowerFieldA": [ "rose", "orchid" ], "flowerFieldB": [ [ "rose", "orchid" ] ], "allValues": [ "orchid", "rose", [ "rose", "orchid" ] ] }
{ "flowerFieldA": [ ], "flowerFieldB": [ ], "allValues": [ ] }
{ "flowerFieldA": [ ], "flowerFieldB": [ "rose" ], "allValues": [ "rose" ] }