MongoDB $setUnion Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Set / Array

What You’ll Learn

The $setUnion operator merges two or more arrays into a single list of unique elements. Use it to combine tags, roles, skills, or permissions from multiple sources without duplicates.

01

Merge Arrays

Combine sets.

02

Remove Dupes

Unique only.

03

Two+ Arrays

Any number.

04

Aggregation

$project / $addFields.

05

Use Cases

Roles, tags.

06

Set Family

Intersect, diff.

Definition and Usage

In MongoDB’s aggregation framework, the $setUnion operator takes two or more arrays and returns every unique element found in any of them. For example, { $setUnion: [ [1, 2, 3], [2, 3, 4] ] } returns [1, 2, 3, 4].

Think of it as combining Venn diagram circles into one set — every value from every array is included, but each value appears only once in the result.

💡
Beginner Tip

Need only shared elements? Use $setIntersection. Need elements in A but not B? Use $setDifference. Need everything combined uniquely? Use $setUnion.

📝 Syntax

The $setUnion operator takes an array of two or more array expressions:

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

Literal Examples

mongosh
{ $setUnion: [ [1, 2, 3], [2, 3, 4] ] }
// Result: [1, 2, 3, 4]

{ $setUnion: [ ["a", "b"], ["b", "b", "c"], ["c", "d"] ] }
// Result: ["a", "b", "c", "d"]  (duplicates removed)

{ $setUnion: [ [1, 2], [3, 4] ] }
// Result: [1, 2, 3, 4]  (no overlap, all included)

Syntax Rules

  • Minimum arrays — at least two array expressions required.
  • Return value — array of all unique elements from every input array.
  • Set semantics — duplicates within or across arrays are removed.
  • Empty arrays — contribute nothing; union of non-empty arrays still works.
  • Returns null if any input array is null.
  • Use inside $project, $addFields, or $set.

💡 $setUnion vs $setIntersection vs $setDifference vs $concatArrays

A = [1,2,3], B = [2,3,4]
$setUnion [A, B] → [1, 2, 3, 4] (all unique)
$setIntersection [A, B] → [2, 3] (in both)
$setDifference [A, B] → [1] (in A only)
$concatArrays [A, B] → [1,2,3,2,3,4] (keeps dupes)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (set / array)
Syntax{ $setUnion: [ arr1, arr2, ... ] }
Minimum arraysTwo
OutputArray of unique combined elements
DuplicatesRemoved automatically
Literals
{
  $setUnion: [
    [1, 2, 3],
    [2, 3, 4]
  ]
}

→ [1, 2, 3, 4]

Fields
{
  $setUnion: [
    "$dbRoles",
    "$ldapRoles"
  ]
}

Merged roles

Three arrays
[
  "$a", "$b", "$c"
]

All combined

Count result
{ $size: "..." }

How many unique

Examples Gallery

Merge role lists from multiple sources, combine user tags, unify permissions, and count unique values with $setUnion.

📚 Merging Role Lists

Combine roles stored in the database with roles from an LDAP directory.

Sample Input Documents

Suppose you have a users collection with roles from two sources:

mongosh
[
  {
    "_id": 1,
    "name": "Alice",
    "dbRoles": ["editor", "viewer"],
    "ldapRoles": ["viewer", "moderator"]
  },
  {
    "_id": 2,
    "name": "Bob",
    "dbRoles": ["admin"],
    "ldapRoles": ["admin", "editor"]
  },
  {
    "_id": 3,
    "name": "Carol",
    "dbRoles": [],
    "ldapRoles": ["viewer"]
  }
]

Example 1 — Merge Database and LDAP Roles

Build a single deduplicated role list for each user:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      dbRoles: 1,
      ldapRoles: 1,
      allRoles: {
        $setUnion: [
          "$dbRoles",
          "$ldapRoles"
        ]
      }
    }
  }
])

How It Works

viewer appears in both source arrays for Alice but only once in the result. Every unique role from either source is included.

📈 Tags, Permissions, and Counting

Combine interest tags, merge permission grants, and measure set size.

Example 2 — Combine User and Article Tags

Build a unified tag list for search indexing or recommendations:

mongosh
db.recommendations.aggregate([
  {
    $project: {
      user: 1,
      combinedTags: {
        $setUnion: [
          "$userTags",
          "$articleTags"
        ]
      }
    }
  }
])

// userTags:    ["mongodb", "nodejs"]
// articleTags: ["mongodb", "database"]
// combinedTags: ["mongodb", "nodejs", "database"]

How It Works

Use the merged list for full-text search facets, content discovery, or feeding into a recommendation engine.

Example 3 — Unify Permissions From Three Sources

Merge permissions from database roles, LDAP groups, and policy grants:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      effectivePermissions: {
        $setUnion: [
          "$dbPermissions",
          "$ldapPermissions",
          "$policyGrants"
        ]
      }
    }
  }
])

How It Works

Pass three or more arrays. Every unique permission from any source appears once in the combined result.

Example 4 — Count Unique Combined Skills

Measure how many distinct skills a candidate has across multiple assessments:

mongosh
db.candidates.aggregate([
  {
    $project: {
      name: 1,
      totalUniqueSkills: {
        $size: {
          $setUnion: [
            "$technicalSkills",
            "$softSkills",
            "$certifications"
          ]
        }
      }
    }
  }
])

How It Works

Wrap $setUnion in $size to get a numeric count of unique combined values.

Bonus — $setUnion vs $concatArrays

See why set union is better when you need deduplication:

mongosh
// $concatArrays — keeps duplicates
{ $concatArrays: [ [1, 2, 3], [2, 3, 4] ] }
// → [1, 2, 3, 2, 3, 4]

// $setUnion — unique combined set
{ $setUnion: [ [1, 2, 3], [2, 3, 4] ] }
// → [1, 2, 3, 4]

How It Works

Use $concatArrays when order and duplicates matter (like concatenating log entries). Use $setUnion when you need a unique membership list.

🚀 Use Cases

  • Access control — merge roles or permissions from multiple identity sources.
  • Content tagging — combine tags from users, articles, and categories.
  • Skill profiles — build a deduplicated skill list from assessments and certifications.
  • Data enrichment — unify values from joined collections without duplicate entries.

🧠 How $setUnion Works

1

MongoDB evaluates each array

All arguments resolve to arrays (field paths, literals, or nested expressions).

Input
2

All elements are collected

Every value from every input array is gathered into one combined set.

Collect
3

Duplicates are removed

Set semantics ensure each value appears only once in the final result array.

Dedupe
=

Union array

Use with $size for counts or store as an enriched field.

Conclusion

The $setUnion operator merges multiple arrays into one deduplicated set. It is the standard tool for combining roles, tags, skills, or permissions from different sources inside aggregation pipelines.

Pair it with $size to count unique combined values. For overlap checks, use $setIntersection; for subtraction, use $setDifference. Next in the series: $sin.

💡 Best Practices

✅ Do

  • Use $setUnion when you need a unique combined membership list
  • Combine with $size to count distinct combined values
  • Handle null arrays with $ifNull when fields may be missing
  • Use $setIntersection when you only need shared elements
  • Normalize string casing before merging tag-like values if needed

❌ Don’t

  • Use $setUnion when you need to preserve duplicate entries
  • Confuse union (all unique) with intersection (in all arrays)
  • Forget that null input arrays return null
  • Expect strict ordering across sources — order follows set rules
  • Use $concatArrays when deduplication is required

Key Takeaways

Knowledge Unlocked

Five things to remember about $setUnion

Use these points when merging arrays as sets in pipelines.

5
Core concepts
📝 02

[ A, B, ... ]

Two+ arrays.

Syntax
🛠 03

No dupes

Set semantics.

Output
🗃 04

+ $size

Count unique.

Chaining
05

vs $concat

Dedupe vs keep.

Compare

❓ Frequently Asked Questions

$setUnion combines two or more arrays and returns every unique element from all of them. Duplicates are removed using set semantics. For example, { $setUnion: [ [1, 2, 3], [2, 3, 4] ] } returns [1, 2, 3, 4].
The syntax is { $setUnion: [ <array1>, <array2>, ... ] }. Each argument is an array expression. You need at least two arrays. The result contains all unique values from every input array.
Yes. $setUnion treats arrays as sets. If the same value appears in multiple input arrays or multiple times within one array, it appears only once in the result.
$setUnion returns all unique elements from any input array (the combined set). $setIntersection returns only elements that appear in every input array (the overlap).
$concatArrays joins arrays end-to-end and keeps duplicates. $setUnion merges arrays as sets and removes duplicates. Use $setUnion when you need a unique combined list.

Continue the Operator Series

Move on to $sin for trigonometric calculations, or review $setIntersection for overlap logic.

Next: $sin →

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