$setUnion (Set Union)
Last updated: 2026-10-09
$setUnion (Set Union)
$setUnion merges all input arrays and deduplicates the elements, returning the union. Typical uses: combining tags from multiple sources or aggregating lead IDs gathered through different channels. It accepts two or more arrays, and null elements are ignored. The result has no guaranteed order, and duplicates collapse to one. Unlike $concatArrays, which keeps duplicates and preserves concatenation order, $setUnion follows set semantics and deduplicates.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $setUnion: [ <array1>, <array2>, ... ] }
⚙️ Parameters
| array | At least two arrays whose union is returned. |
|---|
Returns:A deduplicated merge of all input elements
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $setUnion: merge two tag sets
db.products.aggregate([
{ $project: {
allTags: { $setUnion: ['$tags', '$extraTags'] }
} }
])
Output:
{ '_id': 1, 'allTags': [ 'a', 'b', 'c', 'd' ] }
📌 Notes
- The result is deduplicated with no guaranteed order
- null elements are ignored
- Use $concatArrays when duplicates and order must be kept
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QHow does it differ from $concatArrays?
A$setUnion deduplicates without ordering; $concatArrays keeps duplicates in order.
QHow many arrays are supported?
ATwo or more.
QIs the result deduplicated?
AYes — under set semantics each element appears once.