MongoDB $concatArrays Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
Array Operations

What You’ll Learn

The $concatArrays operator merges multiple arrays into one array in MongoDB aggregation pipelines. Use it to combine tags, skills, categories, or any list fields stored separately in your documents.

01

Merge Arrays

Join lists end-to-end.

02

Syntax

Array of array expressions.

03

Null Safe

Null → empty array.

04

$project Stage

Build unified lists.

05

Use Cases

Tags, skills, defaults.

06

vs $concat

Arrays vs strings.

Definition and Usage

In MongoDB’s aggregation framework, the $concatArrays operator concatenates multiple arrays into a single array. For example, { $concatArrays: [["js", "mongo"], ["node"]] } returns ["js", "mongo", "node"]. Elements keep their order: all items from the first array, then the second, and so on.

💡
Beginner Tip

Do not confuse $concatArrays with $concat. $concat joins strings into one string. $concatArrays joins arrays into one array.

📝 Syntax

The $concatArrays operator takes an array of array expressions:

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

Syntax Rules

  • $concatArrays — returns one array containing all elements in order.
  • Arguments — field references ("$tags"), literal arrays ([1, 2]), or nested expressions.
  • Use inside stages like $project, $addFields, or $set.
  • null or missing array fields are treated as empty arrays.
  • Non-array values cause an aggregation error.
  • Does not flatten nested arrays — only merges at the top level.

💡 $concatArrays vs $concat

$concatArrays["a", "b"] + ["c"]["a", "b", "c"]
$concat"a" + "b""ab"
Arrays vs strings — pick the operator that matches your data type

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (array)
Syntax{ $concatArrays: [ arr1, arr2, ... ] }
Input typesArrays only
Null / missingTreated as empty array []
Common stages$project, $addFields, $set
Two fields
{
  $concatArrays: ["$a", "$b"]
}

Merge field arrays

With default
{
  $concatArrays: ["$tags", ["new"]]
}

Append literal array

Literals
{
  $concatArrays: [[1,2], [3]]
}

Returns [1, 2, 3]

Null field
null → []

Safe to merge

Examples Gallery

Merge tag lists, combine skills from multiple fields, and append default values using $concatArrays.

📚 Merge Two Arrays

Use a products collection and combine separate tag arrays with $project.

Sample Input Documents

Suppose you have a products collection with two tag arrays per document:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "name": "Laptop",
    "primaryTags":   ["electronics", "computers"],
    "secondaryTags": ["sale", "featured"]
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "name": "Mouse",
    "primaryTags":   ["electronics", "accessories"],
    "secondaryTags": null
  }
]

Example 1 — Basic $concatArrays on Fields

Merge primaryTags and secondaryTags into one allTags array:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      allTags: {
        $concatArrays: [ "$primaryTags", "$secondaryTags" ]
      }
    }
  }
])

How It Works

  • Laptop: both arrays merge → four tags total.
  • Mouse: secondaryTags is null, treated as [] → only primary tags appear.

📈 Practical Patterns

Combine skills, append defaults, and merge three or more arrays.

Example 2 — Null and Missing Fields

When secondaryTags is null or missing, $concatArrays treats it as an empty array. The Laptop document merges four tags; the Mouse document keeps only its primary tags:

mongosh
// Mouse document: secondaryTags is null
{ "name": "Mouse", "allTags": ["electronics", "accessories"] }

// If secondaryTags were missing entirely, result is the same

This differs from $concat, where null makes the entire result null.

Example 3 — Combine Skills from Multiple Fields

Merge technical and soft skills into one list for search indexing:

mongosh
db.candidates.aggregate([
  {
    $project: {
      name: 1,
      allSkills: {
        $concatArrays: [ "$technicalSkills", "$softSkills" ]
      }
    }
  }
])

// technicalSkills: ["MongoDB", "Node.js"]
// softSkills:      ["communication", "teamwork"]
// allSkills:       ["MongoDB", "Node.js", "communication", "teamwork"]

How It Works

Order is preserved: all elements from the first array, then all from the second. Use $setUnion afterward if you need unique values only.

Example 4 — Append a Default Array

Always add a default category tag to every product:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      allTags: {
        $concatArrays: [
          "$primaryTags",
          "$secondaryTags",
          ["catalog"]
        ]
      }
    }
  }
])

// Every document gets "catalog" appended to its tag list

How It Works

Literal arrays work as arguments. This pattern is useful for injecting system tags, default permissions, or baseline categories into every merged result.

Example 5 — Merge Three or More Arrays

Combine multiple list fields in one expression:

mongosh
db.events.aggregate([
  {
    $project: {
      title: 1,
      allAttendees: {
        $concatArrays: [
          "$organizers",
          "$speakers",
          "$guests"
        ]
      },
      attendeeCount: {
        $size: {
          $concatArrays: [
            "$organizers",
            "$speakers",
            "$guests"
          ]
        }
      }
    }
  }
])

How It Works

You can pass any number of arrays. Pair with $size to count total elements, or $setUnion to remove duplicates across the merged list.

🚀 Use Cases

  • Tag merging — combine primary and secondary tag arrays for unified search.
  • Skill lists — merge technical and soft skills into one profile array.
  • Default values — append system tags or baseline permissions to every document.
  • Report building — unify list fields from multiple sources before $unwind or grouping.

🧠 How $concatArrays Works

1

MongoDB resolves each array

Field references and literals are evaluated. Null or missing fields become empty arrays.

Input
2

$concatArrays merges in order

Elements from array 1 come first, then array 2, and so on. Nested arrays are not flattened.

Merge
3

The combined array is stored

The result is written to the field you define in $project or $addFields.

Output
=

Single unified array

Ready for $unwind, $size, $setUnion, or further processing.

Conclusion

The $concatArrays operator is the go-to tool for merging array fields in MongoDB aggregation pipelines. It preserves element order, handles null fields gracefully, and works with any number of input arrays.

For beginners, remember: use $concatArrays for arrays and $concat for strings. Use $setUnion when you need unique values after merging.

💡 Best Practices

✅ Do

  • Use $concatArrays when merging list-type fields
  • Append default arrays with literal values when needed
  • Follow with $setUnion to remove duplicates
  • Use $size to count merged elements
  • Remember null fields become empty arrays (unlike $concat)

❌ Don’t

  • Confuse $concatArrays with $concat
  • Pass non-array values (strings, numbers) as arguments
  • Expect nested arrays to be flattened automatically
  • Assume duplicates are removed (use $setUnion)
  • Merge very large arrays without considering document size limits

Key Takeaways

Knowledge Unlocked

Five things to remember about $concatArrays

Use these points when merging arrays in MongoDB.

5
Core concepts
📝 02

Array Syntax

{ $concatArrays: [a, b] }

Syntax
📏 03

Null = []

Safe unlike $concat.

Behavior
🛠 04

Order Preserved

First array, then second.

Property
05

Not $concat

Arrays, not strings.

Important

❓ Frequently Asked Questions

$concatArrays merges multiple arrays into a single array. Elements from the first array come first, followed by elements from the second, and so on.
The syntax is { $concatArrays: [ <array1>, <array2>, ... ] }. Each argument can be a field reference like "$tags" or a literal array like [1, 2].
$concat joins strings into one string. $concatArrays joins arrays into one array. They work on different data types.
$concatArrays treats null or missing array fields as empty arrays. The merge continues without error.
Yes, but $concatArrays only merges at the top level. It does not flatten nested arrays — [1, [2, 3]] stays nested inside the result.

Continue the Operator Series

Move on to $cond for conditional logic, or review $concat for string joining.

Next: $cond →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful