For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
See how MongoDB 9.0 delivers up to 2x higher throughput.
MongoDB Branding Shape
Register now >
Docs Menu

$setUnion (accumulator operator)

$setUnion

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: "<array field>" }

$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.

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:

  • Uses $unwind to create a separate document for each director credit.

  • Uses $match to filter for three specific directors.

  • Uses $group to group by director, count the movies with $sum, and combine the genres arrays of all of the director's movies into a single array of unique genres with $setUnion.

  • Uses $sort to sort results by director name.

  • $setUnion only supports arrays and expressions that resolve to an array.