Bird
Raised Fist0
MongoDBquery~10 mins

$addToSet for unique array additions in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - $addToSet for unique array additions
Start Update
Check if value exists in array?
Skip add
Update document
Done
When updating a document, $addToSet checks if the value is already in the array. If not, it adds it uniquely.
Execution Sample
MongoDB
db.users.updateOne(
  { _id: 1 },
  { $addToSet: { hobbies: "reading" } }
)
This adds "reading" to the hobbies array only if it's not already there.
Execution Table
StepCurrent hobbies arrayValue to addExists in array?ActionResulting hobbies array
1["sports", "music"]"reading"NoAdd "reading"["sports", "music", "reading"]
2["sports", "music", "reading"]"reading"YesSkip add["sports", "music", "reading"]
3["sports", "music", "reading"]"music"YesSkip add["sports", "music", "reading"]
4["sports", "music", "reading"]"travel"NoAdd "travel"["sports", "music", "reading", "travel"]
5["sports", "music", "reading", "travel"]"sports"YesSkip add["sports", "music", "reading", "travel"]
6["sports", "music", "reading", "travel"]"cooking"NoAdd "cooking"["sports", "music", "reading", "travel", "cooking"]
7["sports", "music", "reading", "travel", "cooking"]"reading"YesSkip add["sports", "music", "reading", "travel", "cooking"]
ExitN/AN/AN/ANo more values to addFinal array unchanged
💡 All values processed; duplicates skipped; unique values added.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5After 6Final
hobbies array["sports", "music"]["sports", "music", "reading"]["sports", "music", "reading"]["sports", "music", "reading"]["sports", "music", "reading", "travel"]["sports", "music", "reading", "travel"]["sports", "music", "reading", "travel", "cooking"]["sports", "music", "reading", "travel", "cooking"]
Key Moments - 3 Insights
Why doesn't $addToSet add a value if it already exists in the array?
Because $addToSet ensures uniqueness by checking if the value is already present before adding. See execution_table rows 2 and 3 where "reading" and "music" are skipped since they exist.
What happens if the array field does not exist in the document?
MongoDB creates the array field and adds the value as the first element. This is not shown in the table but is important to know.
Can $addToSet add multiple values at once?
Yes, by using $each inside $addToSet. This example shows single values added one by one for clarity.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the hobbies array after step 4?
A["sports", "music", "reading", "travel"]
B["sports", "music", "reading"]
C["sports", "music", "reading", "travel", "cooking"]
D["sports", "music"]
💡 Hint
Check the Resulting hobbies array column at step 4 in the execution_table.
At which step does the value "cooking" get added to the hobbies array?
AStep 3
BStep 6
CStep 2
DStep 5
💡 Hint
Look for the row where the Action is 'Add "cooking"' in the execution_table.
If we tried to add "music" again, what would happen according to the execution_table?
AIt would be added again, duplicating the value.
BThe array would be cleared first.
CIt would be skipped because it already exists.
DAn error would occur.
💡 Hint
See steps where the value exists and the action is 'Skip add' in the execution_table.
Concept Snapshot
$addToSet operator adds a value to an array only if it is not already present.
Syntax: { $addToSet: { field: value } }
Ensures array uniqueness without duplicates.
Can use $each to add multiple unique values.
If array field missing, it creates it with the value.
Useful for maintaining unique lists in documents.
Full Transcript
$addToSet is a MongoDB update operator that adds a value to an array only if that value does not already exist in the array. When you run an update with $addToSet, MongoDB checks the current array values. If the value is missing, it adds it. If the value is already present, it skips adding to avoid duplicates. This behavior helps keep arrays unique inside documents. The execution table shows step-by-step how values like "reading" and "travel" get added only once, while duplicates like "music" are skipped. If the array field does not exist, MongoDB creates it and adds the value. You can also add multiple unique values at once using $each inside $addToSet. This operator is useful for managing unique lists such as tags, hobbies, or categories in your MongoDB documents.

Practice

(1/5)
1. What is the main purpose of the $addToSet operator in MongoDB?
easy
A. To sort the elements of an array
B. To remove duplicate values from an array
C. To replace an entire array with a new value
D. To add a value to an array only if it does not already exist

Solution

  1. Step 1: Understand the purpose of $addToSet

    $addToSet adds a value to an array only if that value is not already present, ensuring uniqueness.
  2. Step 2: Compare with other array operations

    Unlike operators that remove duplicates or replace arrays, $addToSet only adds unique values without duplicates.
  3. Final Answer:

    To add a value to an array only if it does not already exist -> Option D
  4. Quick Check:

    $addToSet ensures unique additions [OK]
Hint: Remember: $addToSet adds only new unique values [OK]
Common Mistakes:
  • Confusing $addToSet with $push which adds duplicates
  • Thinking $addToSet removes duplicates from existing array
  • Assuming $addToSet sorts the array
2. Which of the following is the correct syntax to add multiple unique values to an array field tags using $addToSet?
easy
A. { $addToSet: { tags: { $each: ["mongodb", "database"] } } }
B. { $addToSet: { tags: ["mongodb", "database"] } }
C. { $addToSet: { tags: { $push: ["mongodb", "database"] } } }
D. { $push: { tags: { $each: ["mongodb", "database"] } } }

Solution

  1. Step 1: Recall syntax for adding multiple unique values

    To add multiple unique values with $addToSet, use $each inside it.
  2. Step 2: Analyze options

    { $addToSet: { tags: { $each: ["mongodb", "database"] } } } correctly uses $addToSet with $each to add multiple unique values. { $addToSet: { tags: ["mongodb", "database"] } } lacks $each, so it tries to add an array as a single element. Using $push inside or instead of $addToSet is incorrect as it doesn't ensure uniqueness.
  3. Final Answer:

    { $addToSet: { tags: { $each: ["mongodb", "database"] } } } -> Option A
  4. Quick Check:

    Use $addToSet with $each for multiple unique additions [OK]
Hint: Use $each inside $addToSet to add multiple unique items [OK]
Common Mistakes:
  • Omitting $each when adding multiple values
  • Using $push instead of $addToSet for uniqueness
  • Adding an array as a single element instead of multiple
3. Given the document { _id: 1, colors: ["red", "blue"] }, what will be the colors array after running this update?
{ $addToSet: { colors: "blue" } }
medium
A. ["red", "blue", "blue"]
B. ["red", "blue"]
C. ["blue"]
D. ["red"]

Solution

  1. Step 1: Understand $addToSet behavior with existing value

    The value "blue" already exists in the array, so $addToSet will not add it again.
  2. Step 2: Determine the resulting array

    Since "blue" is present, the array remains unchanged as ["red", "blue"].
  3. Final Answer:

    ["red", "blue"] -> Option B
  4. Quick Check:

    Existing values are not duplicated by $addToSet [OK]
Hint: If value exists, $addToSet does not add it again [OK]
Common Mistakes:
  • Assuming $addToSet always appends the value
  • Confusing $addToSet with $push which allows duplicates
  • Thinking the array will be replaced
4. You want to add multiple unique tags to a document's tags array, but your update query:
{ $addToSet: { tags: ["nodejs", "mongodb"] } }
adds the entire array as one element instead of separate tags. What is the fix?
medium
A. Use $addToSet: { tags: { $each: ["nodejs", "mongodb"] } }
B. Use $push: { tags: ["nodejs", "mongodb"] }
C. Use $addToSet: { tags: "nodejs", "mongodb" }
D. Use $addToSet: { tags: { $push: ["nodejs", "mongodb"] } }

Solution

  1. Step 1: Identify the problem with adding an array directly

    Adding an array directly with $addToSet adds it as a single element, not multiple elements.
  2. Step 2: Use $each to add multiple unique elements

    Wrapping the array with $each inside $addToSet adds each element uniquely.
  3. Final Answer:

    Use $addToSet: { tags: { $each: ["nodejs", "mongodb"] } } -> Option A
  4. Quick Check:

    Use $each inside $addToSet for multiple unique additions [OK]
Hint: Wrap multiple values with $each inside $addToSet [OK]
Common Mistakes:
  • Adding array directly without $each
  • Using $push instead of $addToSet for uniqueness
  • Incorrect syntax with multiple keys inside $addToSet
5. You have a MongoDB document:
{ _id: 1, items: ["apple", "banana"] }
You want to add the items ["banana", "cherry", "apple", "date"] uniquely to the items array. Which update query will correctly add only the new unique items?
hard
A. { $addToSet: { items: ["banana", "cherry", "apple", "date"] } }
B. { $set: { items: ["banana", "cherry", "apple", "date"] } }
C. { $addToSet: { items: { $each: ["banana", "cherry", "apple", "date"] } } }
D. { $push: { items: { $each: ["banana", "cherry", "apple", "date"] } } }

Solution

  1. Step 1: Understand the goal to add only new unique items

    We want to add only items not already in the array, so duplicates like "banana" and "apple" should not be added again.
  2. Step 2: Choose the correct operator and syntax

    Using $addToSet with $each adds multiple unique items. { $addToSet: { items: { $each: ["banana", "cherry", "apple", "date"] } } } correctly uses this syntax. { $addToSet: { items: ["banana", "cherry", "apple", "date"] } } adds the entire array as one element. { $push: { items: { $each: ["banana", "cherry", "apple", "date"] } } } uses $push which allows duplicates. { $set: { items: ["banana", "cherry", "apple", "date"] } } replaces the entire array, losing existing items.
  3. Final Answer:

    { $addToSet: { items: { $each: ["banana", "cherry", "apple", "date"] } } } -> Option C
  4. Quick Check:

    $addToSet with $each adds only new unique items [OK]
Hint: Use $addToSet with $each to add multiple unique items without duplicates [OK]
Common Mistakes:
  • Adding array directly without $each causing one element addition
  • Using $push which allows duplicates
  • Replacing array with $set losing existing data