$concatArrays (aggregation)

Definition

  • $concatArrays

New in version 3.2.

Concatenates arrays to return the concatenated array.

$concatArrays has the following syntax:

  1. { $concatArrays: [ <array1>, <array2>, ... ] }

The <array> expressions can be any valid expression as long as they resolve to an array. Formore information on expressions, see Expressions.

If any argument resolves to a value of null or refers to a fieldthat is missing, $concatArrays returns null.

Behavior

ExampleResults
  1. { $concatArrays: [ [ "hello", " "], [ "world" ]] }
  1. [ "hello", " ", "world" ]
  1. { $concatArrays: [ [ "hello", " "], [ [ "world" ], "again"]] }
  1. [ "hello", " ", [ "world" ], "again" ]

Example

A collection named warehouses contains the following documents:

  1. { "_id" : 1, instock: [ "chocolate" ], ordered: [ "butter", "apples" ] }
  2. { "_id" : 2, instock: [ "apples", "pudding", "pie" ] }
  3. { "_id" : 3, instock: [ "pears", "pecans"], ordered: [ "cherries" ] }
  4. { "_id" : 4, instock: [ "ice cream" ], ordered: [ ] }

The following example concatenates the instock and the orderedarrays:

  1. db.warehouses.aggregate([
  2. { $project: { items: { $concatArrays: [ "$instock", "$ordered" ] } } }
  3. ])
  1. { "_id" : 1, "items" : [ "chocolate", "butter", "apples" ] }
  2. { "_id" : 2, "items" : null }
  3. { "_id" : 3, "items" : [ "pears", "pecans", "cherries" ] }
  4. { "_id" : 4, "items" : [ "ice cream" ] }

See also

$push