MongoDB $setIsSubset Operator

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

What You’ll Learn

The $setIsSubset operator checks whether the first array is a subset of the second — every element in array1 must also appear in array2. Use it for role validation, skill requirements, tag whitelists, and permission checks.

01

Subset Check

A contained in B?

02

Boolean

true or false.

03

Two Arrays

Exactly two inputs.

04

Set Semantics

Order ignored.

05

Use Cases

Roles, skills, tags.

06

Set Family

Equals, union.

Definition and Usage

In MongoDB’s aggregation framework, the $setIsSubset operator compares two arrays as sets and returns true when every element in the first array is also present in the second. For example, { $setIsSubset: [ [1, 2], [1, 2, 3, 4] ] } returns true because 1 and 2 are both in the second array.

Read it as “Is A contained in B?” — not the other way around. If A has an element that B lacks, the result is false. An empty first array is always a subset of any second array.

💡
Beginner Tip

To verify a candidate has all required skills, put requiredSkills first and candidateSkills second: { $setIsSubset: [ "$requiredSkills", "$candidateSkills" ] }.

📝 Syntax

The $setIsSubset operator takes exactly two array expressions:

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

Literal Examples

mongosh
{ $setIsSubset: [ [1, 2], [1, 2, 3, 4] ] }
// true — 1 and 2 are both in the second array

{ $setIsSubset: [ [1, 2, 5], [1, 2, 3, 4] ] }
// false — 5 is not in the second array

{ $setIsSubset: [ [], [1, 2, 3] ] }
// true — empty set is subset of any set

{ $setIsSubset: [ [1, 2], [2, 1] ] }
// true — order does not matter

Syntax Rules

  • Exactly two arrays — first is tested against second.
  • Return valuetrue if every element of array1 is in array2; otherwise false.
  • Set semantics — order and duplicates in either array are ignored.
  • Empty first array — always returns true.
  • Returns null if either input array is null.
  • Use inside $project, $addFields, $match (with $expr), or $cond.

💡 $setIsSubset vs $setEquals vs $setIntersection

A = [1, 2], B = [1, 2, 3, 4]
$setIsSubset [A, B] → true (A is inside B)
$setIsSubset [B, A] → false (B is not inside A)
$setEquals [A, B] → false (different sets)
$setIntersection [A, B] → [1, 2] (shared elements)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (set / array)
Syntax{ $setIsSubset: [ arr1, arr2 ] }
Array countExactly two
Outputtrue or false
MeaningEvery element of arr1 is in arr2
Common stages$project, $match + $expr, $cond
Literals
{
  $setIsSubset: [
    [1, 2],
    [1, 2, 3, 4]
  ]
}

→ true

Skills
{
  $setIsSubset: [
    "$requiredSkills",
    "$candidateSkills"
  ]
}

Has all required

Roles
{
  $setIsSubset: [
    "$userRoles",
    "$allowedRoles"
  ]
}

Role validation

Empty set
[ [], "$any" ]

→ true

Examples Gallery

Validate user roles against allowed lists, check job skill requirements, filter qualified candidates, and label compliance with $setIsSubset.

📚 Role and Permission Validation

Check whether a user’s roles are contained in an allowed role list.

Sample Input Documents

Suppose you have a users collection:

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

Example 1 — Check If Roles Are Allowed

Verify every role in roles appears in allowedRoles:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      roles: 1,
      allowedRoles: 1,
      rolesAllowed: {
        $setIsSubset: [
          "$roles",
          "$allowedRoles"
        ]
      }
    }
  }
])

How It Works

Each value in the first array must exist in the second. Bob has superuser, which is not allowed, so the result is false.

📈 Recruitment and Filtering

Skill requirements, tag whitelists, and qualified-candidate filters.

Example 2 — Candidate Has All Required Skills

Put required skills first and candidate skills second:

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

// requiredSkills:  ["mongo", "node"]
// candidateSkills: ["mongo", "node", "react"]
// meetsRequirements: true

// candidateSkills: ["mongo"]
// meetsRequirements: false (missing "node")

How It Works

Order matters for which array is the subset. Required skills must all appear in the candidate’s skill list.

Example 3 — Article Tags Within Whitelist

Ensure every article tag is on the approved list:

mongosh
db.articles.aggregate([
  {
    $project: {
      title: 1,
      tagsValid: {
        $setIsSubset: [
          "$tags",
          "$approvedTags"
        ]
      }
    }
  }
])

// tags: ["mongodb", "tutorial"]
// approvedTags: ["mongodb", "tutorial", "news"]
// tagsValid: true

How It Works

Useful for content moderation: reject or flag articles where any tag falls outside the whitelist.

Example 4 — Filter Qualified Candidates

Keep only applications where the candidate meets all skill requirements:

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

How It Works

Wrap $setIsSubset in $expr inside $match to filter documents at query time.

Bonus — Label Status With $cond

Assign a readable compliance label from the subset check:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      status: {
        $cond: [
          {
            $setIsSubset: [
              "$roles",
              "$allowedRoles"
            ]
          },
          "compliant",
          "invalid roles"
        ]
      }
    }
  }
])

How It Works

Combine with $cond for audit reports and admin dashboards that need human-readable status text.

🚀 Use Cases

  • Access control — verify user roles are within an allowed role set.
  • Recruitment — confirm candidates have all required skills.
  • Content moderation — ensure tags or categories stay within a whitelist.
  • Policy compliance — check permission arrays are contained in policy grants.

🧠 How $setIsSubset Works

1

MongoDB evaluates two arrays

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

Input
2

Each array is treated as a set

Duplicates are ignored and order does not matter for either array.

Normalize
3

Every element of A is checked against B

If any value in the first array is missing from the second, the result is false.

Compare
=

true or false

Use in projections, filters, or conditional logic.

Conclusion

The $setIsSubset operator checks whether the first array is contained in the second using set semantics. It returns true when every element of array1 appears in array2.

Use it for role validation, skill requirements, and tag whitelists. Remember argument order: put the smaller or required set first. Next in the series: $setUnion.

💡 Best Practices

✅ Do

  • Put the subset (required / smaller set) first and the superset second
  • Use $setIsSubset for “has all of” checks
  • Wrap in $expr when filtering with $match
  • Use $ifNull to treat missing arrays as [] when appropriate
  • Use $setEquals when both arrays must be exactly the same set

❌ Don’t

  • Reverse the arrays accidentally — [B, A] is not the same as [A, B]
  • Confuse subset with equality — A ⊆ B does not mean A equals B
  • Forget that [] as the first array always returns true
  • Expect null input to return false — null arrays return null
  • Use $setIntersection when you only need a boolean answer

Key Takeaways

Knowledge Unlocked

Five things to remember about $setIsSubset

Use these points when checking whether one array is contained in another.

5
Core concepts
📝 02

[ A, B ]

Exactly two.

Syntax
🛠 03

Order matters

First ⊆ second.

Rule
🗃 04

[] first

Always true.

Edge case
05

vs $setEquals

Subset vs equal.

Compare

❓ Frequently Asked Questions

$setIsSubset returns true when every element in the first array also appears in the second array. It treats arrays as sets, so order and duplicates are ignored. For example, { $setIsSubset: [ [1, 2], [1, 2, 3, 4] ] } returns true.
The syntax is { $setIsSubset: [ <array1>, <array2> ] }. It takes exactly two array expressions. The result is true when array1 is a subset of array2 (every value in array1 is contained in array2).
Yes. The empty array [] is a subset of every array, so { $setIsSubset: [ [], [1, 2, 3] ] } returns true. This follows standard set theory.
$setIsSubset checks whether the first array is contained in the second (A ⊆ B). $setEquals checks whether two or more arrays contain exactly the same set of elements. Equal sets satisfy both directions of subset.
$setIsSubset returns true or false. $setIntersection returns the actual shared elements as an array. If $setIsSubset [A, B] is true, then $setIntersection [A, B] equals A (as sets).

Continue the Operator Series

Move on to $setUnion to combine unique elements from multiple arrays, or review $setIntersection.

Next: $setUnion →

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