$concatArrays

The `$concatArrays` operator is used to combine multiple arrays into a single array. This operator is useful when you need to merge arrays from different documents or fields in a document.

Syntax

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

Parameters

<array1>, <array2>stringrequired

The array fields targeted for concatenation.

Examples

Sample Data

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
  "sales": {
    "salesByCategory": [
      { "categoryName": "DJ Headphones", "totalSales": 35921 }
    ]
  },
  "promotionEvents": [
    {
      "discounts": [
        { "categoryName": "DJ Turntables", "discountPercentage": 18 }
      ]
    }
  ]
}

Concatenate discount arrays

Combine discount arrays from multiple promotion events into a single array.

Query:

db.stores.aggregate([
  { $match: { _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" } },
  {
    $project: {
      name: 1,
      allDiscounts: {
        $concatArrays: [
          { $arrayElemAt: ["$promotionEvents.discounts", 0] },
          { $arrayElemAt: ["$promotionEvents.discounts", 1] }
        ]
      }
    }
  }
])

Output:

[
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "name": "Lakeshore Retail | DJ Equipment Stop",
    "allDiscounts": [
      { "categoryName": "DJ Turntables", "discountPercentage": 18 }
    ]
  }
]