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

$concatArrays (accumulator operator)

$concatArrays

Returns a single array that concatenates the array values of a field across a group of documents.

The $concatArrays accumulator is available in these stages:

Note

Disambiguation

This page describes $concatArrays when used as an accumulator. Accumulators return a single aggregated value across a group of input documents.

You can also use $concatArrays in these other contexts:

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

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 $concatArrays to concatenate the genres arrays of movies grouped by release year:

db.movies.aggregate( [
{
$match: { year: { $in: [1928, 1929] } }
},
{
$group: {
_id: "$year",
combinedGenres: { $concatArrays: "$genres" }
}
},
{ $sort: { _id: 1 } }
] )

The operation uses $match to select movies released in 1928 and 1929, then groups the results by year. The combinedGenres field concatenates the genres arrays of all movies in each year group.

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