How to Use $addToSet Operator in MongoDB: Syntax and Examples
Use the
$addToSet operator in MongoDB to add a value to an array only if it does not already exist in that array. It helps prevent duplicate entries when updating documents with array fields.Syntax
The $addToSet operator is used inside an update command to add a value to an array field only if it is not already present. It has this basic form:
{ $addToSet: { field: value } }- addsvalueto the array infieldif not already there.
mongodb
db.collection.updateOne(
{ <filter> },
{ $addToSet: { <arrayField>: <valueToAdd> } }
)Example
This example shows how to add a unique tag to a document's tags array. If the tag already exists, it won't be added again.
mongodb
db.products.insertOne({ _id: 1, name: "Notebook", tags: ["stationery", "office"] })
// Add a new tag "school" if not present
db.products.updateOne(
{ _id: 1 },
{ $addToSet: { tags: "school" } }
)
// Try to add "office" again - no duplicate added
db.products.updateOne(
{ _id: 1 },
{ $addToSet: { tags: "office" } }
)
// Find the document to see the tags
db.products.findOne({ _id: 1 })Output
{
"_id" : 1,
"name" : "Notebook",
"tags" : [ "stationery", "office", "school" ]
}
Common Pitfalls
Common mistakes when using $addToSet include:
- Using
$pushinstead, which adds duplicates. - Trying to add multiple values without using
$each, which causes errors. - Not specifying the correct array field, leading to no changes.
To add multiple unique values, use $each inside $addToSet.
mongodb
/* Wrong: adds duplicates */ db.products.updateOne( { _id: 1 }, { $push: { tags: "office" } } ) /* Right: adds multiple unique values */ db.products.updateOne( { _id: 1 }, { $addToSet: { tags: { $each: ["home", "office"] } } } )
Quick Reference
| Operator | Purpose | Notes |
|---|---|---|
| $addToSet | Add unique value(s) to an array | Prevents duplicates |
| $addToSet with $each | Add multiple unique values | Use $each to add many values |
| $push | Add value(s) to array | Allows duplicates |
| $pull | Remove value(s) from array | Removes matching values |
Key Takeaways
Use $addToSet to add values to an array only if they don't exist already.
To add multiple unique values, combine $addToSet with $each.
Avoid $push if you want to prevent duplicates in arrays.
Always specify the correct array field when using $addToSet.
$addToSet helps keep array data clean and unique in MongoDB documents.