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.
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 evaluate 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 } }
] )
[
{
_id: 1928,
combinedGenres: [
'Drama', 'War',
'Drama', 'Drama',
'History', 'War',
'Drama', 'Animation',
'Family', 'Comedy',
'Drama', 'Romance',
'Western', 'Short',
'Drama'
]
},
{
_id: 1929,
combinedGenres: [
'Drama', 'Musical',
'Drama', 'Musical',
'Romance', 'Biography',
'Drama', 'History',
'Drama', 'Musical',
'Drama', 'Comedy',
'Short'
]
}
]

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.