$setDifference (Set Difference)
Last updated: 2026-10-09
$setDifference (Set Difference)
$setDifference returns elements present in the first array but absent from the second, with duplicates removed. Typical uses: finding products a user bought but did not favorite, or diffing two name lists. Both arguments must be arrays, and null elements are ignored. The result has no guaranteed order, and relative positions after deduplication are not preserved. Set operators treat arrays as sets, forming a family with $setIntersection and $setUnion.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $setDifference: [ <arrayA>, <arrayB> ] }
⚙️ Parameters
| array A | The set to subtract from. |
|---|---|
| array B | The set to subtract. |
Returns:An array (deduplicated) of elements in A but not in B; null when either argument is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $setDifference: bought but not favorited
db.users.aggregate([
{ $project: {
notFav: { $setDifference: ['$bought', '$favorites'] }
} }
])
Output:
{ '_id': 1, 'notFav': [ 'skuB' ] }
📌 Notes
- The result is deduplicated with no guaranteed order; never rely on positions
- null elements are ignored and do not affect the result
- Both arguments must be arrays or the operator throws
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QIs the result deduplicated?
AYes — under set semantics each element appears once.
QDoes the result keep input order?
ANo guarantee — do not rely on ordering downstream.
QHow is it different from $filter?
A$filter removes by condition per element; $setDifference computes a set difference against another array.