MongoDB $concatArrays Operator
MongoDB provides different types of array expression operators that are used in the aggregation pipeline stages and $concatArrays operator is one of them. This operator is used to concatenate two or more arrays and return a concatenated array.
Syntax:
{ $concatArrays: [ <array1>, <array2>, ... <arrayN>] }
Here, the array must be a valid expression until it resolves to an array. If the argument of this operator is a missing field or the argument resolve to a null value, then this operator will give null.
Examples:
In the following examples, we are working with:
Database: w3wiki
Collection: arrayExample
Document: three documents that contain the details in the form of field-value pairs.
Using $concatArrays Operator:
In this example, we are going to concatenate the values(i.e., arrays) of numbers1 and numbers2 fields using $concatArrays operator.
db.arrayExample.aggregate([ ... {$match: {name: "Lolo"}}, ... {$project: { ... concatResult: {$concatArrays: ["$numbers1", "$numbers2"]}}}])
In this example, we are going to concatenate the values(i.e., arrays) of fruits and veggie fields using $concatArrays operator.
db.arrayExample.aggregate([ ... {$match: {name: "Bongo"}}, ... {$project: {concatResult: ... {$concatArrays: ["$fruits", "$veggie"]}}}])
Using $concatArrays Operator in the Embedded Document:
In this example, we are going to concatenate the value(i.e., array) of favGame.indoorGames field with the specified array(i.e., [“Uno”, “Snooker”]) using $concatArrays operator.
db.arrayExample.aggregate([{$match: {name: "Piku"}}, ... {$project: {concatResult: { ... $concatArrays: ["$favGame.indoorGames", ["Uno", "Snooker"]]}}}])
Contact Us