Definition
Returns a single array that concatenates two or more arrays.
Note
Disambiguation
This page describes $concatArrays when used as an expression, which concatenates two or more arrays into a single array within a single document.
You can also use $concatArrays in these other contexts:
$concatArrays (accumulator), which concatenates the array values from a field across a group of documents.$concatArrays (window function), which is used in the$setWindowFieldsstage to concatenate the array values from a field across a window of documents.
Syntax
When used as an expression, $concatArrays has the following syntax:
{ $concatArrays: [ <expression1>, <expression2>, ... ] }
Behavior
The <expression> operands can be any valid expression if they resolve to an array. For more information on expressions, see Expressions.
If any argument resolves to a value of null or refers to a field that is missing, $concatArrays returns null.
The following table shows how $concatArrays handles arrays and nested arrays:
Example | 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 following pipeline concatenates the genres and writers arrays of the movie "The Godfather":
db.movies.aggregate( [ { $match: { title: "The Godfather" } }, { $project: { _id: 0, title: 1, combinedMovieInfo: { $concatArrays: [ "$genres", "$writers" ] } } } ] )
The operation uses $match to find "The Godfather" and $concatArrays to combine its genres and writers arrays into a single combinedMovieInfo array.
Limitations
$concatArrays only supports arrays and expressions that resolve to an array.