MongoDB $setUnion Operator

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

What Is $setUnion?

$setUnion is a MongoDB aggregation expression that merges two or more arrays into one array of unique values—every element that appears in any input. Order and duplicates are ignored (set semantics).

Remember
$setUnion = unique values from any input array

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

{ $setUnion: [ [1, 2], [2, 3] ] }           → [1, 2, 3]
{ $setUnion: [ ["a","a"], ["a","b"] ] }     → ["a", "b"]
{ $setUnion: [ [], [1, 2] ] }               → [1, 2]

output order is unspecified
nested arrays compared as whole elements
NeedPrefer
All unique values from any array$setUnion
Only shared values$setIntersection
Join arrays keep duplicates$concatArrays

How to Use $setUnion in MongoDB

Pass two or more array expressions. The result is their unique combined set.

  1. Choose an expression stage ($addFields or $project).
  2. Write { $setUnion: [ "$courseA", "$courseB" ] }.
  3. Read the array of unique values from all inputs.
  4. To filter on the result, use $match with $expr.
PieceRequired?Role
Array argumentsYes (2+)Sources to merge as a set
Result—One array of unique values
Order—Not guaranteed

Pseudocode

Pseudocode
for each document:
    result = empty set
    for each input array:
        for each value in that array:
            add value to result   // duplicates ignored
    emit { ..., field: result as array }   // order unspecified

Cheat Sheet

Keep these facts handy while merging arrays as sets.

TopicDetail
TypeAggregation expression (also usable as a $group accumulator)
Syntax{ $setUnion: [ "$a", "$b" ] }
MeaningUnique values from any input
Order / dupesIgnored (set semantics)
Empty inputContributes nothing; others still merge
Related$setIntersection, $setDifference, $concatArrays
Sample check["html","css"] ∪ ["css","js"] → html, css, js

Live Preview

Watch $setUnion merge arrays into one unique set.

Simulates { $setUnion: [ A, B, ... ] } with set semantics (order/dupes ignored).

Result
A = ["html", "css"]
B = ["css", "js"]

$setUnion → ["html", "css", "js"]

{ skills: ["html", "css", "js"] }

Worked Walkthrough — Merge Course Skills

Course A taught ["html", "css"]. Course B taught ["css", "js"]. What unique skills does the student have?

Calculation
A = [ "html", "css" ]
B = [ "css", "js" ]

Start empty set: { }
Add from A: html, css
Add from B: css (already there), js

$setUnion → [ "html", "css", "js" ]
            (order may differ in MongoDB)

MongoDB Examples

We use two students with skills from two courses. First we store them, then we merge the skill lists, then we keep students who learned js. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine two students. Asha learned HTML/CSS then CSS/JS. Ben learned Python then Python/SQL. We save both in a collection named students.

mongosh
db.students.insertMany([
  {
    _id: 1,
    name: "Asha",
    courseA: ["html", "css"],
    courseB: ["css", "js"]
  },
  {
    _id: 2,
    name: "Ben",
    courseA: ["python"],
    courseB: ["python", "sql"]
  }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps two documents in students. Run find() to see them:

mongosh
db.students.find()

Read those documents like this:

Field in MongoDBExample (Asha)Plain English
_id1Document id
name"Asha"Student name
courseA["html", "css"]Skills from the first course
courseB["css", "js"]Skills from the second course
Picture
Asha:
  courseA ∪ courseB
  {html, css} ∪ {css, js}  →  {html, css, js}

Ben:
  courseA ∪ courseB
  {python} ∪ {python, sql} →  {python, sql}

How It Works

  1. Insert once. insertMany adds two student documents to students.
  2. Two skill arrays. Each course contributes its own list; overlap (like css) is expected.
  3. find() shows both rows. What you inserted is what you get back—ready for the union next.

Example 2 — Merge Skills

Goal: add a skills field—the unique set of all course skills.

mongosh
db.students.aggregate([
  {
    $addFields: {
      skills: {
        $setUnion: ["$courseA", "$courseB"]
      }
    }
  }
]);

How It Works

  1. Read both arrays. Still using courseA and courseB from Example 1.
  2. Pass them to $setUnion. Every unique value from either list is kept.
  3. Duplicates drop. Shared values like css or python appear once.
  4. Keep all fields. $addFields adds skills next to the original arrays (order may vary).

Example 3 — Filter with $expr

Keep only students whose combined skills include js.

mongosh
db.students.aggregate([
  {
    $match: {
      $expr: {
        $in: [
          "js",
          { $setUnion: ["$courseA", "$courseB"] }
        ]
      }
    }
  },
  {
    $project: {
      name: 1,
      courseA: 1,
      courseB: 1
    }
  }
]);

How It Works

  1. Union first. Build the unique skill set from both courses (same idea as Example 2).
  2. Test membership. $in checks whether "js" is in that set.
  3. Wrap with $expr. Aggregation operators need $expr inside $match.
  4. Keep matches only. Asha stays; Ben is dropped.

Edge Cases & Pitfalls

Check these before using $setUnion in production pipelines.

order

Output order is not guaranteed

Do not assume the result matches input order. Sort later if you need a stable sequence.

nested

Nested arrays are not flattened

["a"] and [["a"]] are different elements. Nested arrays count as whole values.

vs concat

Not the same as $concatArrays

$concatArrays keeps duplicates and preserves order. Use $setUnion only when uniqueness matters.

types

Every argument must be an array

Non-array inputs error the pipeline. Confirm field types before merging.

Performance Notes

ApproachCostBest for
$setUnion on small arraysCheap per documentTags, skills, category lists
+ $match / $exprScan + expressionFiltering on the merged set
Huge arraysMore unique trackingKeep lists lean when possible

Unions on typical tag/skill arrays are inexpensive compared with large sorts or joins. Filter early with $match when only some documents need the merge.

Key Takeaways

  • Role: merge arrays into one unique set.
  • Syntax: { $setUnion: [ A, B, ... ] }.
  • Set rules: order and duplicates ignored.
  • vs concat: use $concatArrays if you need duplicates kept.

One line: $setUnion answers “what unique values appear in any of these arrays?”

Frequently Asked Questions

$setUnion combines two or more arrays and returns every unique element that appears in any of them. Duplicates are removed. For example, { $setUnion: [ [1, 2], [2, 3] ] } returns an array containing 1, 2, and 3 (order may vary).
As an array operator: { $setUnion: [ <array1>, <array2>, ... ] }. Each argument must resolve to an array. On newer MongoDB versions it can also be used as a $group accumulator: { $setUnion: "$field" }.
Yes. Arrays are treated as sets. Values that appear more than once across inputs appear only once in the result.
$concatArrays joins arrays end-to-end and keeps duplicates. $setUnion merges them as sets and removes duplicates. Use $setUnion when you need a unique combined list.
$setUnion returns elements in any input array (combined set). $setIntersection returns only elements that appear in every input array (overlap).
No. The order of elements in the result is unspecified. Do not rely on a particular sequence—sort later if you need one.

Next: $sin

Compute the sine of an angle expressed in radians.

$sin 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