MongoDB $setIntersection Operator

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

What Is $setIntersection?

$setIntersection is a MongoDB aggregation expression that returns the unique elements shared by every input array. Arrays are treated as sets—duplicates are ignored; only the overlap remains.

Remember
$setIntersection = values in ALL arrays

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

[1, 2, 3] ∩ [2, 3, 4] → [2, 3]
["a","a","b"] ∩ ["b"] → ["b"]
no overlap → []

duplicates ignored
null / missing arg → null

vs $setUnion → combine unique values
UsePrefer
Shared elements$setIntersection
All unique elements$setUnion
Same set? (boolean)$setEquals

How to Use $setIntersection in MongoDB

Pass two or more arrays and keep only the values that appear in every one.

  1. Choose an expression stage ($addFields or $project).
  2. Pass the arrays to compare (fields and/or literals).
  3. Read the result array (empty [] means no overlap).
  4. Use $setUnion when you want the combined unique list instead.
PieceRequired?Role
Array 1YesFirst set (order often followed)
Array 2+YesOther sets to intersect
Result—Array of shared unique values (or null)

Pseudocode

Pseudocode
for each document:
    arrays = evaluate each argument
    if any array is null or missing:
        result = null
    else:
        result = unique values present in every array
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while finding shared array values.

TopicDetail
TypeAggregation expression (returns an array)
Syntax{ $setIntersection: [ a, b, ... ] }
MeaningElements in all inputs
DuplicatesIgnored
No overlap[]
vs $setUnionOverlap vs combined uniques
Sample["math","quiz","art"] ∩ ["quiz","math"] → ["math","quiz"]

Live Preview

Intersect two skill lists and see the shared values (set rules).

Simulates { $setIntersection: [a, b] }.

Result
a = ["math", "quiz", "art"]
b = ["quiz", "math", "science"]

$setIntersection → ["math", "quiz"]

Worked Walkthrough — Shared Skills

Asha has skills math, quiz, art. The course requires quiz, math, science. The overlap is math and quiz.

Calculation
skills   = ["math", "quiz", "art"]
required = ["quiz", "math", "science"]

math     → in both ✓
quiz     → in both ✓
art      → only skills ✗
science  → only required ✗

$setIntersection → ["math", "quiz"]
  (order follows first array)

MongoDB Examples

We use one student with a skills list and a required list. First insert the sample, then compute the intersection, then contrast with $setUnion. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine student Asha with skills: ["math", "quiz", "art"] and required: ["quiz", "math", "science"]. We save the document in students.

mongosh
db.students.insertOne({
  _id: 1,
  name: "Asha",
  skills: ["math", "quiz", "art"],
  required: ["quiz", "math", "science"]
});

How the Data Is Stored in MongoDB

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

mongosh
db.students.find()

Read that document like this:

Field in MongoDBValuePlain English
_id1Document id
name"Asha"Student name
skills["math", "quiz", "art"]What she has
required["quiz", "math", "science"]What the course needs
Picture
skills:   math  quiz  art
required: quiz  math  science
                ↓
shared:   math  quiz

How It Works

  1. Insert once. insertOne adds Asha’s document to students.
  2. Two arrays ready. We will keep only values that appear in both.
  3. find() shows the same shape. Ready for Example 2.

Example 2 — Intersection

Goal: add shared = $setIntersection of skills and required.

mongosh
db.students.aggregate([
  {
    $addFields: {
      shared: {
        $setIntersection: ["$skills", "$required"]
      }
    }
  }
]);

How It Works

  1. Read both arrays. Still using the lists from Example 1.
  2. Keep the overlap. Only math and quiz appear in both.
  3. Store the array. $addFields writes shared: ["math", "quiz"].

Example 3 — Contrast with $setUnion

Same document, but also compute $setUnion so you can see overlap vs combined unique values.

mongosh
db.students.aggregate([
  {
    $addFields: {
      shared: { $setIntersection: ["$skills", "$required"] },
      allUnique: { $setUnion: ["$skills", "$required"] }
    }
  }
]);

How It Works

  1. Intersection. Values in both lists → ["math", "quiz"].
  2. Union. Every unique value from either list → adds art and science.
  3. Pick the right tool. Overlap → $setIntersection; combined set → $setUnion.

Edge Cases & Pitfalls

Check these before intersecting arrays in production pipelines.

empty

No overlap → []

An empty array means “no shared values,” not an error. Check length if your logic needs a match.

dupes

Duplicates are ignored

["a","a","b"] ∩ ["b"] is still ["b"]. Counts do not carry over.

null

Null args → null

A missing or null array makes the whole result null, not [].

order

Don’t rely on fancy ordering

Common values usually follow the first array’s order. Sort explicitly if your UI needs a fixed sequence.

Performance Notes

ApproachCostBest for
$setIntersection on small arraysCheap set compareTags / skills overlap
Huge arraysGrows with unique sizeKeep lists lean
Filter then intersectFewer docsLarge collections

Intersecting short tag lists is inexpensive. Filter early with $match when only some documents need the check.

Key Takeaways

  • Role: unique values present in every array.
  • Empty overlap: returns [].
  • vs $setUnion: overlap vs combined uniques.
  • Sample: skills ∩ required → ["math", "quiz"].

One line: $setIntersection answers “which unique values appear in every array I passed?”

Frequently Asked Questions

$setIntersection returns the unique elements that appear in every input array. Arrays are treated as sets, so duplicates are ignored. Example: { $setIntersection: [ [1, 2, 3], [2, 3, 4] ] } returns [2, 3].
Use { $setIntersection: [ <array1>, <array2>, ... ] }. Pass two or more array expressions. The result contains only values present in all of them.
It uses set semantics. Common elements usually appear in the order they show up in the first array. Duplicates in the inputs are ignored.
$setIntersection returns the overlap (in all arrays). $setUnion returns every unique value from any array (the combined set).
$setIntersection returns the shared elements as an array. $setEquals returns true or false for whether the arrays are the same set.
If any argument is null or refers to a missing field, $setIntersection returns null.

Next: $setIsSubset

Test whether all values of one array appear in another.

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