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

CategorySet, Condition & Conversion
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $setDifference: [ <arrayA>, <arrayB> ] }

⚙️ Parameters

array AThe set to subtract from.
array BThe 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏