For AI agents: a documentation index is available at https://www.mongodb.com/zh-cn/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

$setUnion (window function)

$setUnion

Returns an array of the unique elements in the array values in a window.

New in version 8.1.

Note

Disambiguation

This page describes $setUnion when used as a window function.

You can also use $setUnion in these other contexts:

  • $setUnion (accumulator), which returns a single array of the unique elements in the array values across a group of documents.

  • $setUnion (expression), which combines two or more arrays into a single array of unique elements.

{
$setWindowFields: {
...
output: {
<field>: {
$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 $setWindowFields to show how the genres in a director's filmography accumulate over time. Each document receives the unique genres from the earliest movie through the current movie.

db.movies.aggregate( [
{
$match: { directors: "Christopher Nolan" }
},
{
$setWindowFields: {
sortBy: { year: 1 },
output: {
genresSoFar: {
$setUnion: "$genres",
window: { documents: [ "unbounded", "current" ] }
}
}
}
},
{
$project: {
_id: 0,
title: 1,
year: 1,
genres: 1,
genresSoFar: 1
}
}
] )

The preceding pipeline:

  • Uses $match to filter for movies directed by Christopher Nolan.

  • Uses $setWindowFields to sort movies by year and apply $setUnion to the genres field over a documents window of [ "unbounded", "current" ]. The genresSoFar field holds the unique genres from the first movie in the sort order through the current movie.

  • Uses $project to include title, year, genres, and genresSoFar in the output.

The genresSoFar array grows as each movie contributes genres that have not yet appeared. The Dark Knight Rises and Interstellar add no new genres, so their windows return the same set as Inception.