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

$concatArrays (expression)

$concatArrays

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:

When used as an expression, $concatArrays has the following syntax:

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

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
{ $concatArrays: [
[ "hello", " " ], [ "world" ]
] }
[ "hello", " ", "world" ]
{ $concatArrays: [
[ "hello", " " ],
[ [ "world" ], "again" ]
] }
[ "hello", " ", [ "world" ], "again" ]

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.

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