MongoDB $setIntersection Operator

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

What You’ll Learn

The $setIntersection operator returns elements that appear in every input array. Use it to find shared tags, overlapping skills, common permissions, or any values present in all sets.

01

Common Elements

In all arrays.

02

Array Syntax

Two+ arrays.

03

Set Semantics

Unique values.

04

Aggregation

$project / $addFields.

05

Use Cases

Match, overlap.

06

Set Family

Union, difference.

Definition and Usage

In MongoDB’s aggregation framework, the $setIntersection operator compares two or more arrays as sets and returns only the elements that appear in all of them. For example, { $setIntersection: [ [1, 2, 3], [2, 3, 4] ] } returns [2, 3].

Think of it as the overlap between sets — the Venn diagram center. If no elements are shared, the result is an empty array [].

💡
Beginner Tip

Need all elements from any array combined? Use $setUnion. Need elements in A but not B? Use $setDifference. Need the overlap? Use $setIntersection.

📝 Syntax

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

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

Literal Examples

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

{ $setIntersection: [ ["a", "b", "c"], ["b", "c", "d"], ["c", "e"] ] }
// Result: ["c"]  (only in all three)

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

Syntax Rules

  • Minimum arrays — at least two array expressions required.
  • Return value — array of elements present in every input array.
  • Set semantics — duplicates in input arrays are ignored.
  • Empty result[] when no elements are shared.
  • Returns null if any input array is null.
  • Use inside $project, $addFields, or $set.

💡 $setIntersection vs $setUnion vs $setDifference vs $setEquals

A = [1,2,3], B = [2,3,4]
$setIntersection [A, B] → [2, 3] (in both)
$setUnion [A, B] → [1, 2, 3, 4] (all unique)
$setDifference [A, B] → [1] (in A only)
$setEquals [A, B] → false (same set?)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (set / array)
Syntax{ $setIntersection: [ arr1, arr2, ... ] }
Minimum arraysTwo
OutputArray of shared elements
No overlap[]
Literals
{
  $setIntersection: [
    [1, 2, 3],
    [2, 3, 4]
  ]
}

→ [2, 3]

Fields
{
  $setIntersection: [
    "$tags",
    "$articleTags"
  ]
}

Shared tags

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

In all three

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

How many shared

Examples Gallery

Find shared tags between users and articles, matching skills for jobs, common permissions, and count overlaps with $setIntersection.

📚 Content Recommendation

Find tags shared between a user’s interests and an article’s tags.

Sample Input Documents

Suppose you have a recommendations collection pairing users with articles:

mongosh
[
  {
    "_id": 1,
    "user": "Alice",
    "userTags": ["mongodb", "nodejs", "database"],
    "articleTags": ["mongodb", "aggregation", "database"]
  },
  {
    "_id": 2,
    "user": "Bob",
    "userTags": ["python", "ml"],
    "articleTags": ["mongodb", "database"]
  },
  {
    "_id": 3,
    "user": "Carol",
    "userTags": ["java", "spring"],
    "articleTags": ["mongodb", "database"]
  }
]

Example 1 — Find Shared Tags

Compute tags that appear in both userTags and articleTags:

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

How It Works

Only tags present in both arrays are returned. Alice gets two matches; Bob and Carol have no overlap with their articles.

📈 Matching and Filtering

Skill overlap, permission checks, and filtering by shared elements.

Example 2 — Matching Skills Between Candidate and Job

Find skills the candidate has that the job also requires:

mongosh
db.applications.aggregate([
  {
    $project: {
      candidate: 1,
      jobTitle: 1,
      matchingSkills: {
        $setIntersection: [
          "$candidateSkills",
          "$requiredSkills"
        ]
      }
    }
  }
])

// candidateSkills: ["mongo", "node", "react"]
// requiredSkills:  ["mongo", "node", "aws"]
// matchingSkills:  ["mongo", "node"]

How It Works

The intersection is the skill overlap — useful for scoring candidates or highlighting qualifications in a UI.

Example 3 — Count Shared Tags

Measure how many tags overlap using $size:

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

// Alice: 2, Bob: 0, Carol: 0

How It Works

$size on the intersection gives a numeric relevance score. Sort by overlapCount descending for best matches first.

Example 4 — Filter Rows With at Least One Shared Tag

Keep only recommendations where user and article share at least one tag:

mongosh
db.recommendations.aggregate([
  {
    $match: {
      $expr: {
        $gt: [
          {
            $size: {
              $setIntersection: [
                "$userTags",
                "$articleTags"
              ]
            }
          },
          0
        ]
      }
    }
  }
])

// Returns Alice only

How It Works

Combine $setIntersection, $size, and $gt inside $expr to filter documents with any overlap.

Bonus — Common to Three Permission Lists

Find permissions granted in all three sources:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      commonPermissions: {
        $setIntersection: [
          "$dbRoles",
          "$ldapGroups",
          "$policyGrants"
        ]
      }
    }
  }
])

// Only permissions present in dbRoles AND
// ldapGroups AND policyGrants

How It Works

Pass three or more arrays. An element must appear in every array to be included in the result.

🚀 Use Cases

  • Recommendations — score content by shared tags or categories.
  • Recruitment — highlight skills that match job requirements.
  • Access control — find permissions common across role sources.
  • Data validation — verify overlap between expected and actual value sets.

🧠 How $setIntersection Works

1

MongoDB evaluates each array

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

Input
2

Sets are compared for overlap

MongoDB finds values that appear in every input array, ignoring duplicates.

Intersect
3

Shared elements are collected

The result array contains only values present in all sets. No overlap yields [].

Output
=

Intersection array

Use with $size for scores or $match for filtering.

Conclusion

The $setIntersection operator finds elements shared by all input arrays using set semantics. It is the go-to tool for overlap, matching, and relevance scoring inside aggregation pipelines.

Pair it with $size to count overlaps, or with $match and $expr to filter documents that share values. Next in the series: $setIsSubset.

💡 Best Practices

✅ Do

  • Use $setIntersection for overlap and matching logic
  • Combine with $size for numeric relevance scores
  • Handle null arrays with $ifNull when fields may be missing
  • Use $setUnion when you need all unique elements combined
  • Normalize string casing before comparing tag-like values if needed

❌ Don’t

  • Expect ordered list intersection — this is set semantics
  • Confuse intersection (in all) with union (in any)
  • Forget that null input arrays return null
  • Assume duplicates in the result — each value appears once
  • Use $setEquals when you need the shared elements array itself

Key Takeaways

Knowledge Unlocked

Five things to remember about $setIntersection

Use these points when finding shared array elements in pipelines.

5
Core concepts
📝 02

[ A, B, ... ]

Two+ arrays.

Syntax
🛠 03

Unique only

Set semantics.

Output
🗃 04

+ $size

Count overlap.

Chaining
05

[]

No shared values.

Edge case

❓ Frequently Asked Questions

$setIntersection returns elements that appear in every input array. It treats arrays as sets, so duplicates are ignored. For example, { $setIntersection: [ [1, 2, 3], [2, 3, 4] ] } returns [2, 3].
The syntax is { $setIntersection: [ <array1>, <array2>, ... ] }. Each argument is an array expression. You need at least two arrays. The result contains only values present in all of them.
The result uses set semantics. Element order generally follows the order of appearance in the first array, but only common elements are kept. Duplicates in input arrays are ignored.
$setIntersection returns elements in all arrays (the overlap). $setUnion returns every unique element from any array (the combined set).
$setIntersection returns the shared elements as an array. $setEquals returns true or false depending on whether two or more arrays contain exactly the same set of elements.

Continue the Operator Series

Move on to $setIsSubset to test whether one array is contained in another, or review $setDifference.

Next: $setIsSubset →

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