Docs Menu

$concatArrays

Returns a single array that concatenates two or more arrays. $concatArrays can be used as an aggregation accumulator or an array operator.

$concatArrays

$concatArrays is available as an accumulator in these stages:

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

{ $concatArrays: "<array field>" }

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.

Create a collection named sales with the following documents:

db.sales.insertMany( [
{
_id: 1,
items: [ "laptop", "tablet" ],
location: "NYC"
},
{
_id: 2,
items: [ "phone", "tablet" ],
location: "NYC"
},
{
_id: 3,
location: "NYC"
},
{
_id: 4,
items: [ "desktop", { "accessories": [ "mouse", "keyboard"] } ],
location: "NYC"
}
] )

This example shows how you can use $concatArrays as an accumulator. This example combines the elements of all items arrays when grouping on the location field:

db.sales.aggregate( [
{
$group: {
_id: "$location",
array: { "$concatArrays": "$items" }
}
}
] )

The operation returns the following result:

[
{
"_id": "NYC",
"array": [
"laptop", "tablet", "phone", "tablet", "desktop",
{ "accessories": [ "mouse", "keyboard"] }
]
}
]
$concatArrays

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

{ $concatArrays: [ <array1>, <array2>, ... ] }

The <array> expressions can be any valid expression as long as 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.

Example
Results
{ $concatArrays: [
[ "hello", " "], [ "world" ]
] }
[ "hello", " ", "world" ]
{ $concatArrays: [
[ "hello", " "],
[ [ "world" ], "again"]
] }
[ "hello", " ", [ "world" ], "again" ]

Create a collection named warehouses with the following documents:

db.warehouses.insertMany( [
{ _id : 1, instock: [ "chocolate" ], ordered: [ "butter", "apples" ] },
{ _id : 2, instock: [ "apples", "pudding", "pie" ] },
{ _id : 3, instock: [ "pears", "pecans" ], ordered: [ "cherries" ] },
{ _id : 4, instock: [ "ice cream" ], ordered: [ ] }
] )

The following example concatenates the instock and the ordered arrays:

db.warehouses.aggregate( [
{ $project: { items: { $concatArrays: [ "$instock", "$ordered" ] } } }
] )

The operation returns the following results:

[
{ _id : 1, items : [ "chocolate", "butter", "apples" ] },
{ _id : 2, items : null },
{ _id : 3, items : [ "pears", "pecans", "cherries" ] },
{ _id : 4, items : [ "ice cream" ] }
]

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