Definition
Returns a single array that concatenates two or more arrays. $concatArrays
can be used as an aggregation accumulator or an array operator.
Aggregation Accumulator
$concatArrays
$concatArrays
is available as an accumulator in these stages:
Syntax
When used as an aggregation accumulator, $concatArrays
has the following syntax:
{ $concatArrays: "<array field>" }
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
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"] }
]
}
]
Array Operator
Syntax
When used as an array operator, $concatArrays
has the following syntax:
{ $concatArrays: [ <array1>, <array2>, ... ] }
Behavior
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 |
---|---|
|
|
|
|
Example
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: