0
0
MongoDBquery~5 mins

$addToSet for unique array additions in MongoDB

Choose your learning style9 modes available
Introduction

$addToSet helps you add items to an array only if they are not already there. It keeps the array unique without duplicates.

When you want to add a new tag to a list of tags but avoid duplicates.
When you keep track of user IDs who liked a post and want to add a new user only once.
When you store unique email addresses in a contact list and want to add new ones safely.
When you update a product's categories and want to add a category only if it is not already assigned.
Syntax
MongoDB
db.collection.updateOne(
  { <filter> },
  { $addToSet: { <arrayField>: <valueToAdd> } }
)

filter selects the document to update.

arrayField is the name of the array you want to add to.

Examples
Adds "reading" to Alice's hobbies only if it is not already there.
MongoDB
db.users.updateOne(
  { name: "Alice" },
  { $addToSet: { hobbies: "reading" } }
)
Adds "swimming" and "cycling" to Bob's hobbies, each only if not already present.
MongoDB
db.users.updateOne(
  { name: "Bob" },
  { $addToSet: { hobbies: { $each: ["swimming", "cycling"] } } }
)
If Charlie has no hobbies array, this creates it and adds "chess".
MongoDB
db.users.updateOne(
  { name: "Charlie" },
  { $addToSet: { hobbies: "chess" } }
)
Sample Program

This program creates a user Diana with two hobbies. It tries to add "jogging" again but it won't duplicate. Then it adds "photography" and tries to add "painting" again. Finally, it prints the document before and after updates.

MongoDB
use testdb

// Insert a sample user document
db.users.insertOne({ name: "Diana", hobbies: ["painting", "jogging"] })

// Show initial document
print("Before update:")
printjson(db.users.findOne({ name: "Diana" }))

// Add a new hobby "jogging" (already exists) - should not add duplicate
// Add a new hobby "photography" (new) - should add

// Update with $addToSet for single value
db.users.updateOne(
  { name: "Diana" },
  { $addToSet: { hobbies: "jogging" } }
)

// Update with $addToSet and $each for multiple values
db.users.updateOne(
  { name: "Diana" },
  { $addToSet: { hobbies: { $each: ["photography", "painting"] } } }
)

// Show updated document
print("After update:")
printjson(db.users.findOne({ name: "Diana" }))
OutputSuccess
Important Notes

$addToSet only adds the value if it is not already in the array, so it prevents duplicates.

Using $each inside $addToSet lets you add multiple unique values at once.

If the array field does not exist, $addToSet creates it with the new value.

Summary

$addToSet keeps arrays unique by adding only new values.

Use $each with $addToSet to add multiple unique items at once.

It is useful to avoid duplicate entries in arrays in MongoDB documents.