翻译或纠错本页面

$setUnion (aggregation)

On this page

Definition

$setUnion

2.6 新版功能.

Takes two or more arrays and returns an array containing the elements that appear in any input array.

$setUnion has the following syntax:

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

The arguments can be any valid expression as long as they each resolve to an array. For more information on expressions, see Expressions.

Behavior

$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 filters out duplicates in its result to output an array that contain only unique entries. The order of the elements in the output array is unspecified.

If a set contains a nested array element, $setUnion does not descend into the nested array but evaluates the array at top-level.

Example   Result
{ $setUnion: [ [ "a", "b", "a" ], [ "b", "a" ] ] }   [ "b", "a" ]
{ $setUnion: [ [ "a", "b" ], [ [ "a", "b" ] ] ] }   [ [ "a", "b" ], "b", "a" ]

Example

Consider an experiments collection with the following documents:

{ "_id" : 1, "A" : [ "red", "blue" ], "B" : [ "red", "blue" ] }
{ "_id" : 2, "A" : [ "red", "blue" ], "B" : [ "blue", "red", "blue" ] }
{ "_id" : 3, "A" : [ "red", "blue" ], "B" : [ "red", "blue", "green" ] }
{ "_id" : 4, "A" : [ "red", "blue" ], "B" : [ "green", "red" ] }
{ "_id" : 5, "A" : [ "red", "blue" ], "B" : [ ] }
{ "_id" : 6, "A" : [ "red", "blue" ], "B" : [ [ "red" ], [ "blue" ] ] }
{ "_id" : 7, "A" : [ "red", "blue" ], "B" : [ [ "red", "blue" ] ] }
{ "_id" : 8, "A" : [ ], "B" : [ ] }
{ "_id" : 9, "A" : [ ], "B" : [ "red" ] }

The following operation uses the $setUnion operator to return an array of elements found in the A array or the B array or both:

db.experiments.aggregate(
   [
     { $project: { A:1, B: 1, allValues: { $setUnion: [ "$A", "$B" ] }, _id: 0 } }
   ]
)

The operation returns the following results:

{ "A": [ "red", "blue" ], "B": [ "red", "blue" ], "allValues": [ "blue", "red" ] }
{ "A": [ "red", "blue" ], "B": [ "blue", "red", "blue" ], "allValues": [ "blue", "red" ] }
{ "A": [ "red", "blue" ], "B": [ "red", "blue", "green" ], "allValues": [ "blue", "red", "green" ] }
{ "A": [ "red", "blue" ], "B": [ "green", "red" ], "allValues": [ "blue", "red", "green" ] }
{ "A": [ "red", "blue" ], "B": [ ], "allValues": [ "blue", "red" ] }
{ "A": [ "red", "blue" ], "B": [ [ "red" ], [ "blue" ] ], "allValues": [ "blue", "red", [ "red" ], [ "blue" ] ] }
{ "A": [ "red", "blue" ], "B": [ [ "red", "blue" ] ], "allValues": [ "blue", "red", [ "red", "blue" ] ] }
{ "A": [ ], "B": [ ], "allValues": [ ] }
{ "A": [ ], "B": [ "red" ], "allValues": [ "red" ] }