$setIntersection (Set Intersection)
Last updated: 2026-10-09
$setIntersection (Set Intersection)
$setIntersection returns the elements present in every input array, with duplicates removed. Typical uses: finding interests shared between a user and friends, or the common products under several filter conditions. It accepts two or more arrays, and null elements are ignored. The result follows set semantics without a guaranteed order, completing the set-operator family with $setUnion (union) and $setDifference (difference).
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $setIntersection: [ <array1>, <array2>, ... ] }
⚙️ Parameters
| array | At least two arrays whose common elements are returned. |
|---|
Returns:A deduplicated array of elements present in every input array
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $setIntersection: shared interest tags
db.users.aggregate([
{ $project: {
common: { $setIntersection: ['$myTags', '$friendTags'] }
} }
])
Output:
{ '_id': 1, 'common': [ 'mongo', 'db' ] }
📌 Notes
- The result is deduplicated with no guaranteed order
- Two or more arrays are supported
- null elements are ignored
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QIs the result deduplicated?
AYes, the intersection deduplicates by set semantics.
QAre multiple arrays supported?
AYes — only elements in every array appear in the result.
QIs the result order guaranteed?
ANo, never rely on the order.