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

$concatArrays (window function)

$concatArrays

Returns an array of the concatenated array values from documents in a window.

Note

Disambiguation

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

You can also use $concatArrays in these other contexts:

{
$setWindowFields: {
...
output: {
<field>: {
$concatArrays: "<array field>"
}
}
}
}

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 following example uses the movies collection from the sample_mflix sample dataset. For details on how to load this dataset into your deployment, see Load the sample dataset.

The example uses $setWindowFields to partition movies by release year and concatenate the genres arrays within each partition, sorted by title. Each document receives the concatenation of the genres arrays from the first movie in its partition through the current document:

db.movies.aggregate( [
{ $match: { year: { $in: [1914, 1915] } } },
{ $setWindowFields: {
partitionBy: { year: "$year" },
sortBy: { title: 1 },
output: {
combinedGenres: {
$concatArrays: "$genres",
window: { documents: ["unbounded", "current"] }
}
}
} },
{ $project: { _id: 0, year: 1, title: 1, combinedGenres: 1 } }
] )

The preceding pipeline:

  • Uses $setWindowFields to partition movies by year with partitionBy and sort each partition by title. The stage applies $concatArrays to the genres field over a documents window of [ "unbounded", "current" ]. The combinedGenres field holds the concatenated genres from the first movie in the partition through the current document.

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

The combinedGenres array grows within each partition as each document contributes its genres array.