$addToSet (Unique Array Accumulator)
Last updated: 2026-10-09
$addToSet (Unique Array Accumulator)
$addToSet is an accumulator that adds each document's expression result to an array during $group, deduplicating automatically — repeated values appear once. Like $push but guarantees uniqueness. Suits tags, customer lists, and other dedup needs. Element order is not guaranteed.
| Category | Accumulators |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $group: { _id: <key>, tags: { $addToSet: "$field" } } }
Returns:Deduplicated array of expression results
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $addToSet: distinct items per customer
db.orders.aggregate([
{ $group: { _id: '$cust_id', items: { $addToSet: '$item' } } }
])
Output:
{ "_id": "A123", "items": ["Pen", "Book"] }
📌 Notes
- Elements are unique; duplicates collapse to one
- Order is not guaranteed; sort yourself if needed
- Deduplication uses BSON value equality (same type and value)
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $addToSet and $push?
A$push keeps duplicates; $addToSet removes them.
QIs the order guaranteed?
ANo, element order is not guaranteed; sort the result yourself.
QCan it deduplicate array elements?
ANot directly — it compares whole array values; $unwind first to flatten.