0
0
MongodbHow-ToBeginner · 3 min read

How to Use $addToSet in MongoDB: Syntax and Examples

In MongoDB, use the $addToSet operator to add a value to an array only if it does not already exist, preventing duplicates. It is used in update operations to maintain unique elements in array fields.
📐

Syntax

The $addToSet operator adds a value to an array only if the value is not already present. It is used inside an update command with the $addToSet operator.

  • field: The array field to update.
  • value: The value to add if it does not exist.
mongodb
db.collection.updateOne(
  { <filter> },
  { $addToSet: { <field>: <value> } }
)
💻

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 it doesn't exist
 db.products.updateOne(
   { _id: 1 },
   { $addToSet: { tags: "school" } }
 )

// Try to add "office" again (won't duplicate)
 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 $addToSet on a field that is not an array, which causes an error.
  • Expecting $addToSet to add multiple values at once without using $each.
  • Not using $each when adding multiple values, which results in adding the entire array as a single element.
mongodb
/* Wrong: adds entire array as one element */
db.collection.updateOne(
  { _id: 1 },
  { $addToSet: { tags: ["new", "sale"] } }
)

/* Right: use $each to add multiple unique values */
db.collection.updateOne(
  { _id: 1 },
  { $addToSet: { tags: { $each: ["new", "sale"] } } }
)
📊

Quick Reference

OperatorDescriptionExample Usage
$addToSetAdds a value to an array only if it does not exist{ $addToSet: { tags: "new" } }
$eachUsed with $addToSet to add multiple unique values{ $addToSet: { tags: { $each: ["new", "sale"] } } }

Key Takeaways

Use $addToSet to add unique values to an array field without duplicates.
To add multiple values uniquely, combine $addToSet with $each.
Ensure the target field is an array before using $addToSet to avoid errors.
$addToSet does not add duplicates, so it helps maintain clean arrays.
Use update operations like updateOne or updateMany with $addToSet.