$addToSet (Add to Set)
Last updated: 2026-10-09
$addToSet (Add to Set)
$addToSet adds a value to an array only if it is not already present, keeping the array free of duplicates. `{ $addToSet: { tags: 'mongodb' } }`. To add several values at once combine with $each. Duplicate detection compares whole values (nested documents field by field). Great for tags and follow lists.
| Category | Update Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $addToSet: { <array field>: <value> } }
⚙️ Parameters
| array field | The array field to add to. |
|---|---|
| value | The value to add; skipped if already present. |
Returns:The update result
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $addToSet: add tag (skipped if present)
db.articles.updateOne(
{ _id: 1 },
{ $addToSet: { tags: 'mongodb' } }
)
// Multiple values need $each
db.articles.updateOne(
{ _id: 1 },
{ $addToSet: { tags: { $each: ['database', 'nosql'] } } }
)
Output:
// Existing mongodb is not duplicated; database and nosql are appended
📌 Notes
- Dedup compares whole values
- Several values at once require $each
- Creates the array if missing; non-array fields throw
🏷️ Related Tags
💡 Related Cases
Array and Nested Document Queries
Hands-On: CRUD for a Blog Comment System
Document Update: A Detailed Explanation of `updateOne` and `updateMany`
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $addToSet and $push?
A$addToSet dedups; $push appends and allows duplicates.
QHow do I add several values at once?
AUse $each: { $addToSet: { tags: { $each: ['a', 'b'] } } }.
QCan $addToSet add nested documents?
AYes; dedup compares the whole document.