MongoDB

MongoDB $ConcatArrays

The $concatArrays is the array expression of MongoDB which is used in the aggregation pipeline method. The $concatArrays operator is used to concatenate the two arrays of documents in a single array. To make a unique array, we can concatenate more than two arrays with the $concatArrays operator. The important point is that the $concatArrays operator only resolves the array fields in MongoDB or else it generates the error. The array has to be a valid statement for $concatArrays before it can be converted to a modified array. The $concatArrays operator returns null if any of the arguments is a nonexistent field or resolves to a null value. This article provides further information on the $concatArrays operator.

How to Use the $ConcatArrays Operator in MongoDB

We use the $concatArrays operator of MongoDB to merge the two arrays as a single array. The $concatArrays operator is used over the “Games” collection document. The “Games” collection of MongoDB is set with the following documents using the insertMany() command. These documents also contain the array fields which are used by the $concatArrays operator here to join them.

db.Games.insertMany([
      {
          "_id": 1,
          "Game":"FootBall",
          "Team1": ["David", "Mark", "Levis"],
          "Team2" : ["Sam", "Alex", "Orchid"],
          "Score1":[20, 14, 8],
          "Score2": [7, 19, 21]
      },
       {
          "_id": 2,
          "Game":"Tennis",
          "Team1": ["Bella", "Emily", "Alice"],
          "Team2" : ["Stella", "Bloom", "Olive"],
          "Score1":[19, 15, 18],
          "Score2": [17, 10, 11]
      },
       {
         "_id": 3,
          "Game":"BasketBall",
          "Team1": ["George", "Smith", "Polard"],
          "Team2" : [],
          "Score1":[21, 15, 6],
          "Score2": [4, 13, 19]
      },
   {
         "_id": 4,
          "Game":"Badminton",
          "Team1": ["David", "Mark", "Levis"],
          "Team2" : 0,
          "Score1":[20, 14, 8],
          "Score2": [7, 19, 21]
      }
  ])

When we run the insertMany() query in the MongoDB shell, it represents the following results:

{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 } }

Example 1: MongoDB $ConcatArrays Operator to Concatenate the Integer Array

We use the MongoDB $concatArrays operator to concatenate the array of the integer elements. Here, we use the $Score1 and $Score2 fields for the operation because they contain the numeric values of the array. We use the aggregate() operator where the $match operator matches the document which satisfies the “{“Game”: “FootBall”}” condition. Then, we utilize the $project operator for the inclusion of the “NewArray” field. The “NewArray” field has the $concatArrays operator which inputs the “$Score1” and “$Score2” array fields. The $concatArrays operator merges the values of these fields only for the document whose “Games” field has the “FootBall” value.

db.Games.aggregate([
    {$match: {"Game": "FootBall"}},
    {$project: {
    NewArray: {$concatArrays: ["$Score1", "$Score2"]}}}])

The array that is displayed in the output against the “NewArray” field contains all the elements of the set field of the $concatArrays. Note that any repeated value is not concatenated twice in the array. It just appears one at a time in the newly generated array by the $concatArrays operator.

[ { _id: 1, NewArray: [ 20, 14, 8, 7, 19, 21 ] } ]

Example 2: MongoDB $ConcatArrays Operator to Concatenate the String Array

We use the $concatArrays operator to join the numerical array values. The $concatArrays operator of MongoDB also merges the string array value in a single array. Just like the integer array, the $concatArrays operator merges the unique elements of the string array. Here, we match the document with the “Tennis” value against the “Games” field. Once the document is matched by the $match operator, we apply the $concatArrays operator on the string array fields, “$Team1” and “$Team2”. The projected “NewArray” field displays the resultant array by the $concatArrays operator.

db.Games.aggregate([
   {$match: {"Game": "Tennis"}},
   {$project: {NewArray:
   {$concatArrays: ["$Team1", "$Team2"]}}}])

The string values of the “$Team1” and “$Team2” fields are concatenated by the $concatArrays operator in the following “NewArray” field:

[
  {
    _id: 2,
    NewArray: [ 'Bella', 'Emily', 'Alice', 'Stella', 'Bloom', 'Olive' ]
  }
]

Example 3: MongoDB $ConcatArrays Operator to Concatenate the Empty Arrays

When the $concatArrays operator joins the array field with another empty field, no changes occur. The array field which contains the values only appears in the new modified array. Let’s consider the working of the $concatArrays operator on the empty array field. We first search the document which has the empty array. The $match operator is used to find the document with the “_id” field and the value of “3”. Then, we have the “ArrayResult” inclusion field which is employed with the $concatArrays operator. The $concatArrays uses the [ “$Team1”, “$Team2” ] expression to merge them in as a unique array.

db.Games.aggregate([
    { $match: { _id: 3 } },
    { $project: {
        _id: 0,
        NewArray: { $concatArrays: [ "$Team1", "$Team2" ] }
        }
    }
])

The resultant array just displays the element of the first array by the $concatArrays operator because the second array is empty.

[ { NewArray: [ 'George', 'Smith', 'Polard' ] } ]

Example 4: MongoDB $ConcatArrays Operator to Concatenate the Arrays of Another Type

The $concatArrays operator only takes the argument as a valid expression to resolve the arrays. MongoDB produces an error if the $concatArrays operator cannot be resolved to an array. Here is the query where the invalid expression is passed in the $concatArrays. We first deploy the $match operator in the aggregate() method which matches the “_id: 4” expression with the documents of the collection that we are working with. After that, we have a $project operator for the suppression of the “_id” field since “0” is allocated to it. Then, we have a new addition of the “ArrayResult” field where the $concatArrays operation is conducted. The $concatArrays operator here inputs “$Team1” the array field which has the string value and the “$Team2” field is not the array. Furthermore, the $Team2 field has a type of integer value.

db.Games.aggregate([
    { $match: { _id: 4 } },
    { $project: {
        _id: 0,
        ArrayResult: { $concatArrays: [ "$Team1", "$Team2" ] }
        }
    }
])

There, we encounter the MongoDB server error as the $concatArrays operator which is trying to join the array with the other type.

“MongoServerError: PlanExecutor error during aggregation :: caused by :: $concatArrays only supports arrays, not int”

Example 5: MongoDB $ConcatArrays Operator to Concatenate the Array of the Missing Field

When the $concatArrays operator is used to join the field array that does not exist in any of the documents, the null is obtained in the output. Consider the statement with the example script. We concatenate the array fields by matching the “_id: 4” document using the $match operator. Then, we have a $project operator that defines the “ResultArr” field. The “ResultArr” field has the $concatArrays operator that is used to join the “$Team1” field that is included in the specified document with the “$Team3” field which is not part of the document.

db.Games.aggregate([
    { $match: { _id: 2 } },
    { $project: {
        _id: 0,
        ResultArr: { $concatArrays: [ "$Team1", "$Team3" ] }
        }
    }
])

When the query is executed in the MongoDB shell, the “null” is retrieved from the $concatOperator because the $Team3 field is not included in the document of “_id: 4”.

[ { ResultArr: null } ]

Conclusion

This article is about the MongoDB $concatArrays operator which joins the array value. We merged the integer arrays and the string arrays with the help of the $concatArrays operator. Then, we employed the $concatArrays operator to concatenate the empty array with the filled array which ended up with the first array element in the output. We also joined the array with the missing array that returns the null value. In the end, we took the case of the $concatArrays operator where we joined the arrays of different types.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.