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: GeeksforGeeks

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 vegiie fields using $concatArrays operator.

db.arrayExample.aggregate([
... {$match: {name: "Bongo"}},
... {$project: {concatResult:
... {$concatArrays: ["$fruits", "$vegiie"]}}}])

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"]]}}}])

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.