Definition
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 (expression), which concatenates two or more arrays into a single array within a single document.$concatArrays (window function), which is used in the$setWindowFieldsstage to concatenate the array values from a field across a window of documents.
Syntax
{ $concatArrays: [ <expression1>, <expression2>, ... ] }
Behavior
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.
Example
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.
Limitations
$concatArrays only supports arrays and expressions that resolve to an array.