Docs 菜单
Docs 主页
/
MongoDB Manual
/ / /

$setUnion(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$setUnion

接受两个或多个数组,并返回一个数组,其中包含出现在每个输入数组中的元素。

$setUnion 通过以下语法实现:

{ $setUnion: [ <expression1>, <expression2>, ... ] }

参数可以是任何有效的表达式,只要它们都能解析为大量即可。 有关表达式的更多信息,请参阅表达式操作符。

$setUnion对数组执行集合操作,将数组视为集合。如果数组包含重复条目,$setUnion 会忽略重复条目。$setUnion 会忽略元素的顺序。

$setUnion 过滤掉结果中的重复项,以输出仅包含唯一条目的数组。 输出数组中元素的顺序未指定。

如果集合包含嵌套数组元素,$setUnion不会下降进入嵌套数组,而是在顶层计算数组。

例子
结果
{ $setUnion: [ [ "a", "b", "a" ], [ "b", "a" ] ] }
[ "b", "a" ]
{ $setUnion: [ [ "a", "b" ], [ [ "a", "b" ] ] ] }
[ [ "a", "b" ], "b", "a" ]

注意

从 MongoDB 5.2 开始,$setUnion 的排序未定义。要对数组排序,请参阅 $sortArray

考虑包含以下文档的 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" ] }

后退

$setIsSubset

在此页面上