MongoDB $concatArrays

In MongoDB, the $concatArrays aggregation pipeline operator concatenates two or more arrays and returns the concatenated array.

Example

Suppose we have a collection called data with the following document:

{ "_id" : 1, "a" : [ 1, 2, 3 ], "b" : [ 4, 5, 6 ] }

We can use the $concatArrays operator to concatenate the array of the a field with the array of the b field:

db.data.aggregate([
    { $match: { _id: 1 } },
    { $project: { 
        _id: 0,
        result: { $concatArrays: [ "$a", "$b" ] }
        }
    }
])

Result:

{ "result" : [ 1, 2, 3, 4, 5, 6 ] }

Empty Arrays

Concatenating an array with an empty array doesn’t change anything.

Suppose our collection also contains the following document:

{ "_id" : 2, "a" : [ 1, 2, 3 ], "b" : [ ] }

Let’s apply $concatArrays to that::

db.data.aggregate([
    { $match: { _id: 2 } },
    { $project: { 
        _id: 0,
        result: { $concatArrays: [ "$a", "$b" ] }
        }
    }
])

Result:

{ "result" : [ 1, 2, 3 ] }

We end up with the first array without any changes.

Missing Fields

Trying to concatenate a field with a field that doesn’t exist returns null.

Imagine our collection also contains the following document:

{ "_id" : 3, "a" : [ 1, 2, 3 ] }

Here’s what happens when we apply $concatArrays to the a field and a non-existent field:

db.data.aggregate([
    { $match: { _id: 3 } },
    { $project: { 
        _id: 0,
        result: { $concatArrays: [ "$a", "$b" ] }
        }
    }
])

Result:

{ "result" : null }

Other Data Types

Each expression provided to $concatArrays can be any valid expression, as long as it resolves to an array.

If it doesn’t resolve to an array, an error is returned.

Suppose we have the following document:

{ "_id" : 4, "a" : [ 1, 2, 3 ], "b" : 4 }

Here’s what happens if we try to concatenate the a and b fields:

db.data.aggregate([
    { $match: { _id: 4 } },
    { $project: { 
        _id: 0,
        result: { $concatArrays: [ "$a", "$b" ] }
        }
    }
])

Result:

Error: command failed: {
	"ok" : 0,
	"errmsg" : "$concatArrays only supports arrays, not double",
	"code" : 28664,
	"codeName" : "Location28664"
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:618:17
assert.commandWorked@src/mongo/shell/assert.js:708:16
DB.prototype._runAggregate@src/mongo/shell/db.js:266:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1046:12
@(shell):1:1

In this example I tried to concatenate an array with a double but I got an error that states $concatArrays only supports arrays, not double.