Introduction to MongoDB $concatArrays Operator
In MongoDB’s aggregation pipeline, the $concatArrays
operator is used to merge two or more arrays into one array.
Syntax
The syntax of the $concatArrays
operator is as follows:
{ `$concatArrays` : [ <expression1>, <expression2>, ... ] }
Where <expression1>
, <expression2>
are the array expressions to be merged.
Use Cases
The $concatArrays
operator is suitable for aggregation operations that require merging multiple arrays. For example, it can merge arrays from different data sources into one array.
Examples
Example 1
The following aggregation pipeline merges data from the sales
and expenses
collections into one array:
db.sales.aggregate([
{
$lookup:
{
from: "expenses",
localField: "quarter",
foreignField: "quarter",
as: "expenses"
}
},
{
$project:
{
_id: 0,
quarter: 1,
sales: 1,
expenses: "$expenses.amount"
}
},
{
$project:
{
_id: 0,
data: { `$concatArrays` : [ "$sales", "$expenses" ] }
}
}
])
After running the above aggregation pipeline, the result is as follows:
{ "data" : [ 100, 200, 300, 50, 75, 100 ] }
Example 2
The following aggregation pipeline uses the $concatArrays
operator to merge two arrays in a document into one array:
db.collection.aggregate([
{
$project:
{
_id: 0,
merged: { `$concatArrays` : [ "$array1", "$array2" ] }
}
}
])
Suppose the original document is as follows:
{ "array1" : [ 1, 2, 3 ], "array2" : [ 4, 5, 6 ] }
After running the above aggregation pipeline, the result is as follows:
{ "merged" : [ 1, 2, 3, 4, 5, 6 ] }
Conclusion
The $concatArrays
operator can merge multiple arrays into one array, which is suitable for aggregation operations that require processing multiple arrays.