MongoDB $setEquals Operator

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

What You’ll Learn

The $setEquals operator checks whether two or more arrays contain the same set of elements and returns true or false. Order and duplicates are ignored — perfect for comparing roles, tags, or permissions.

01

Set Compare

Same elements?

02

Boolean

true or false.

03

Order Free

[1,2] = [2,1].

04

Two+ Arrays

All must match.

05

Use Cases

Roles, tags, ACLs.

06

vs $eq

Set vs ordered.

Definition and Usage

In MongoDB’s aggregation framework, the $setEquals operator compares two or more arrays as sets. It returns true when every array contains exactly the same unique elements, and false when they differ. For example, { $setEquals: [ [1, 2, 3], [3, 2, 1] ] } returns true.

This is different from $eq, which compares arrays in order. Use $setEquals when you care about membership, not sequence — such as verifying that a user’s roles match a template or that two tag lists are equivalent.

💡
Beginner Tip

Duplicates are ignored: [1, 1, 2] and [2, 1] are equal sets. If you need exact ordered array equality, use $eq instead.

📝 Syntax

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

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

Literal Examples

mongosh
{ $setEquals: [ [1, 2, 3], [3, 2, 1] ] }
// true — same set, different order

{ $setEquals: [ ["admin", "user"], ["user", "admin"] ] }
// true

{ $setEquals: [ [1, 2], [2, 3] ] }
// false — different elements

{ $setEquals: [ [1, 2], [1, 2], [2, 1] ] }
// true — all three match

Syntax Rules

  • Minimum arrays — at least two array expressions required.
  • Return valuetrue if all arrays represent the same set; otherwise false.
  • Order ignored[a, b] equals [b, a].
  • Duplicates ignored — set semantics apply to each array.
  • Returns null if any input array is null.
  • Use inside $project, $addFields, $match (with $expr), or $cond.

💡 $setEquals vs $eq vs $setDifference

[1, 2, 3] vs [3, 2, 1]$setEquals: true, $eq: false
$setEquals — boolean; same set of unique elements?
$eq — boolean; same array values in same order?
$setDifference [A, B] empty AND [B, A] empty → sets are equal (same idea as $setEquals)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (set / array)
Syntax{ $setEquals: [ arr1, arr2, ... ] }
Outputtrue or false
Order matters?No
Common stages$project, $match + $expr, $cond
Literals
{
  $setEquals: [
    [1, 2, 3],
    [3, 2, 1]
  ]
}

→ true

Fields
{
  $setEquals: [
    "$roles",
    "$expectedRoles"
  ]
}

Role check

$match
$expr: {
  $setEquals: ["$a", "$b"]
}

Filter docs

Not equal
false

Different sets

Examples Gallery

Compare user roles to templates, verify tag lists, filter matching documents, and branch with $cond using $setEquals.

📚 Role and Permission Checks

Verify whether a user’s roles match an expected role set.

Sample Input Documents

Suppose you have a users collection:

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

Example 1 — Check If Roles Match Expected Set

Add a boolean flag comparing roles and expectedRoles:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      roles: 1,
      expectedRoles: 1,
      rolesMatch: {
        $setEquals: [
          "$roles",
          "$expectedRoles"
        ]
      }
    }
  }
])

How It Works

$setEquals ignores order and duplicates. Alice’s ["admin", "editor"] matches ["editor", "admin"].

📈 Filtering and Branching

Find documents with matching tag sets and label compliance status.

Example 2 — Filter Users With Matching Roles

Keep only documents where roles equal expected roles:

mongosh
db.users.aggregate([
  {
    $match: {
      $expr: {
        $setEquals: [
          "$roles",
          "$expectedRoles"
        ]
      }
    }
  },
  {
    $project: { name: 1, roles: 1 }
  }
])

// Returns Alice and Carol only

How It Works

Wrap $setEquals in $expr inside $match so MongoDB evaluates it as an aggregation expression.

Example 3 — Compare Product Tag Sets

Check whether a product’s tags match a category template:

mongosh
db.products.aggregate([
  {
    $lookup: {
      from: "categories",
      localField: "categoryId",
      foreignField: "_id",
      as: "category"
    }
  },
  { $unwind: "$category" },
  {
    $project: {
      name: 1,
      tagsMatchCategory: {
        $setEquals: [
          "$tags",
          "$category.requiredTags"
        ]
      }
    }
  }
])

How It Works

After $lookup, compare the product’s tags with the category’s required tag set. Useful for catalog validation rules.

Example 4 — Label Status With $cond

Assign a human-readable status from the comparison result:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      compliance: {
        $cond: [
          {
            $setEquals: [
              "$roles",
              "$expectedRoles"
            ]
          },
          "compliant",
          "review needed"
        ]
      }
    }
  }
])

How It Works

$cond uses the boolean from $setEquals as its condition. This pattern works well in audit and access-control reports.

Bonus — Compare Three Arrays at Once

Verify that three role sources all agree:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      allSourcesAgree: {
        $setEquals: [
          "$roles",
          "$ldapRoles",
          "$expectedRoles"
        ]
      }
    }
  }
])

// true only when all three arrays are the same set

How It Works

Pass more than two arrays. Every array must represent the same set for the result to be true.

🚀 Use Cases

  • Access control — verify user roles match expected or template roles.
  • Tag validation — confirm product or content tags match category requirements.
  • Data sync checks — compare arrays from different sources (LDAP, DB, cache).
  • Compliance reporting — flag documents where permission sets diverge from policy.

🧠 How $setEquals Works

1

MongoDB evaluates each array

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

Input
2

Each array is treated as a set

Duplicates are removed and order is ignored for comparison purposes.

Normalize
3

All sets are compared

If every array contains exactly the same unique elements, the result is true.

Compare
=

true or false

Use in projections, filters, or conditional logic.

Conclusion

The $setEquals operator compares arrays as sets and returns true when they contain the same unique elements. Order and duplicates do not affect the result.

Use it for role checks, tag validation, and sync verification. For elements in A but not B, use $setDifference. Next in the series: $setField.

💡 Best Practices

✅ Do

  • Use $setEquals when order and duplicates should not matter
  • Wrap in $expr when filtering with $match
  • Use $ifNull to treat missing arrays as [] when appropriate
  • Compare three or more sources in one expression when they must all agree
  • Use $eq when exact ordered array equality is required

❌ Don’t

  • Expect [1, 2] and [2, 1] to differ — they are equal sets
  • Use $setEquals for ordered list comparison (use $eq)
  • Forget that null input arrays return null, not false
  • Assume case-insensitive string matching unless values are normalized
  • Confuse set equality with subset checks (see $setIsSubset in MongoDB docs)

Key Takeaways

Knowledge Unlocked

Five things to remember about $setEquals

Use these points when comparing arrays as sets in pipelines.

5
Core concepts
📝 02

[ A, B, ... ]

Two+ arrays.

Syntax
🛠 03

Order ignored

Set semantics.

Rule
🗃 04

vs $eq

Set vs ordered.

Compare
05

null in

null out.

Edge case

❓ Frequently Asked Questions

$setEquals returns true when all input arrays contain the same set of elements, and false otherwise. Order and duplicate values are ignored — [1, 2, 3] and [3, 2, 1] are considered equal.
The syntax is { $setEquals: [ <array1>, <array2>, ... ] }. You can compare two or more arrays. Each argument is an array expression (field path or literal).
No. $setEquals uses set semantics. Element order does not matter. Only which unique values are present counts.
$eq compares arrays element-by-element in order — [1, 2] and [2, 1] are not equal with $eq. $setEquals treats arrays as sets, so order and duplicates are ignored.
$setEquals checks whether arrays represent the same set (boolean). $setDifference returns elements in the first array but not others. $setIntersection returns shared elements. If $setDifference [A, B] is empty and $setDifference [B, A] is empty, the sets are equal.

Continue the Operator Series

Move on to $setField for dynamic field access, or review $setDifference for set subtraction.

Next: $setField →

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