MongoDB $concatArrays Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $concatArrays?

$concatArrays is a MongoDB aggregation expression that joins two or more arrays into one array. Order is preserved: first array’s elements, then the next, and so on. It does not remove duplicates or flatten nested arrays.

Remember
$concatArrays = [...a, ...b] for aggregation

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

["a","b"] + ["c"] → ["a","b","c"]
keeps duplicates
does not deep-flatten

null / missing argument → null
non-array (except null) → pipeline error
UsePrefer
Join arrays in order$concatArrays
Join strings$concat
Unique merge (set-style)$setUnion

How to Use $concatArrays in MongoDB

List the arrays to join, wrap them in one outer array, and emit the result.

  1. Choose an expression stage ($addFields or $project).
  2. Collect two or more array expressions (fields or literals).
  3. Pass them to $concatArrays in the order you want.
  4. If a field might be missing, wrap it with $ifNull and default to [].
PieceRequired?Role
$concatArraysYesJoin arrays end-to-end
Array of arraysYes (≥ 2 typical)Each item must resolve to an array (or null)
$ifNullNoTreat missing/null as []

Pseudocode

Pseudocode
for each document:
    arrays = evaluate each argument
    if any argument is null or missing:
        result = null
    else if any argument is not an array:
        error
    else:
        result = []
        append every element from array1, then array2, ...
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while joining arrays.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $concatArrays: [ <a>, <b>, ... ] }
OrderLeft to right; original element order kept
DuplicatesKept (not unique)
Null ruleAny null/missing → result null
vs $concatStrings vs arrays
Sample check["Pen"] + ["Ink"] → ["Pen","Ink"]

Live Preview

Watch $concatArrays join a cart and a wishlist into one list.

Simulates { $concatArrays: [ cart, wishlist ] }.

Result
cart = ["Notebook", "Pen"]
wishlist = ["Marker", "Eraser"]
$concatArrays → ["Notebook", "Pen", "Marker", "Eraser"]

Worked Walkthrough — Cart + Wishlist

One shopper has items in the cart and more on a wishlist. We want one combined list.

Calculation
Document:
  {
    cart: ["Notebook", "Pen"],
    wishlist: ["Marker", "Eraser"]
  }

Join left to right:
  cart     → Notebook, Pen
  wishlist → Marker, Eraser

$concatArrays →
  ["Notebook", "Pen", "Marker", "Eraser"]

MongoDB Examples

We use one shopping document. First join two fields, then join three arrays (including a literal). Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one order draft with a cart and a wishlist. We save both arrays in a collection named shopping.

mongosh
db.shopping.insertOne({
  _id: 1,
  shopper: "Asha",
  cart: ["Notebook", "Pen"],
  wishlist: ["Marker", "Eraser"]
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in shopping. Run find() to see it:

mongosh
db.shopping.find()

Read that document like this:

Field in MongoDBValuePlain English
_id1Document id (row number for this lesson)
shopper"Asha"Who is shopping
cart["Notebook", "Pen"]Items already in the cart
wishlist["Marker", "Eraser"]Items still on the wishlist
Picture
cart:     [ Notebook, Pen ]
wishlist: [ Marker, Eraser ]
                 |
                 v
all_items:
  [ Notebook, Pen, Marker, Eraser ]

How It Works

  1. Insert once. insertOne adds a single shopping document to shopping.
  2. MongoDB stores arrays as written. cart and wishlist keep their order.
  3. find() shows the same shape. What you inserted is ready for $concatArrays next.

Example 2 — Join Two Fields

Goal: build all_items by joining cart then wishlist.

mongosh
db.shopping.aggregate([
  {
    $addFields: {
      all_items: {
        $concatArrays: ["$cart", "$wishlist"]
      }
    }
  }
]);

How It Works

  1. Read both arrays. MongoDB already has cart and wishlist from Example 1.
  2. Append in order. $concatArrays copies cart items first, then wishlist items.
  3. Keep originals. $addFields adds all_items without deleting cart or wishlist.

Example 3 — Join Three Arrays

Same document, but also append a literal promo list at the end.

mongosh
db.shopping.aggregate([
  {
    $addFields: {
      all_items: {
        $concatArrays: [
          "$cart",
          "$wishlist",
          ["Ruler"]
        ]
      }
    }
  }
]);

How It Works

  1. Same stored document. Still using Asha’s cart and wishlist from Example 1.
  2. Three sources. Fields first, then the literal ["Ruler"].
  3. Easy check. Four stored items plus one promo item → five elements in all_items.

Edge Cases & Pitfalls

Check these before using $concatArrays in production pipelines.

null

Null or missing → null

One null argument makes the whole result null. Default with $ifNull to [] when empty is safer.

dup

Duplicates are kept

Joining ["A","B"] and ["B","C"] yields two "B" values. Use $setUnion for unique values.

nest

No deep flatten

Nested arrays stay nested. $concatArrays only joins the top-level arrays you pass in.

type

Need strings? Use $concat

$concat is for strings. Passing strings to $concatArrays errors.

Performance Notes

ApproachCostBest for
$concatArrays of fieldsO(total elements) per docSmall lists on each document
Many large arraysLarger memory per docAvoid building huge combined arrays if unused
+ $size / $sliceExtra cheap opsCount or trim after joining

Joining short arrays is cheap. Filter early with $match when only some documents need a combined list.

Key Takeaways

  • Role: join arrays end-to-end in order.
  • Duplicates: kept; use $setUnion for unique.
  • Nulls: any null/missing → result is null.
  • Strings: use $concat, not $concatArrays.

One line: $concatArrays is pipeline spread—stick arrays together in order without unique or flatten magic.

Frequently Asked Questions

$concatArrays joins two or more arrays into one array. Elements from the first array come first, then the second, and so on. Use it inside aggregation stages such as $project and $addFields.
Use { $concatArrays: [ <array1>, <array2>, ... ] }. Pass an array of array expressions—field paths, literals, or nested expressions.
$concat joins strings. $concatArrays joins arrays. They work on different types.
If any argument is null or refers to a missing field, $concatArrays returns null. Use $ifNull to supply [] when you want to treat missing as empty.
No. It keeps every element in order, including duplicates. Use $setUnion when you want a unique set-style merge.
No. Only the top-level arrays are joined. Nested arrays stay nested inside the result.

Next: $cond

Write if/then/else logic inside an aggregation pipeline.

$cond tutorial →

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.

9 people found this page helpful