定义
行为
$setUnion performs set operation on arrays, treating arrays as sets. If an array contains duplicate entries, $setUnion ignores the duplicate entries. $setUnion ignores the order of the elements.
$setUnion 过滤掉结果中的重复项,以输出仅包含唯一条目的数组。 输出数组中元素的顺序未指定。
If a set contains a nested array element, $setUnion does not descend into the nested array but evaluates the array at top-level.
例子 | 结果 | ||
|---|---|---|---|
| | ||
| |
注意
Starting in MongoDB 5.2, the sort order for $setUnion is undefined. To sort an array, refer to $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" ] } ] )
The following operation uses the $setUnion operator to return an array of elements found in the flowerFieldA array or the flowerFieldB array or both:
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" ] }