Definition
Returns an array of the unique elements in the array values across a group of documents.
New in version 8.1.
The $setUnion accumulator is available in these stages:
Note
Disambiguation
This page describes $setUnion when used as an accumulator. Accumulators return a single aggregated value across a group of input documents.
You can also use $setUnion in these other contexts:
$setUnion (expression), which combines two or more arrays into a single array of unique elements.$setUnion (window function), which is used in the$setWindowFieldsstage to return a single array of the unique elements in the array values in a window.
Syntax
{ $setUnion: "<array field>" }
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 contains 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.
To see how $setUnion treats nested array elements, see the examples in the $setUnion (expression) section.
Arguments that are null or resolve to null are included in the results. Arguments that refer to a field that is missing are not included in the results.
Example
The examples on this page use data from the sample_mflix dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the Sample Dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
This example uses $setUnion to return the distinct genres that three specific directors have worked in:
db.movies.aggregate( [ { $unwind: "$directors" }, { $match: { directors: { $in: [ "Christopher Nolan", "Sofia Coppola", "Spike Lee" ] } } }, { $group: { _id: "$directors", movieCount: { $sum: 1 }, genres: { $setUnion: "$genres" } } }, { $sort: { _id: 1 } } ] )
The preceding pipeline:
Limitations
$setUniononly supports arrays and expressions that resolve to an array.