Consider a MongoDB document with the field tags as ["red", "blue"]. You run this update:
{ $addToSet: { tags: "green" } }What will be the new value of tags?
Remember, $addToSet adds the value only if it is not already present.
The $addToSet operator adds the value "green" to the tags array only if it does not exist. Since "green" is not in the array, it is added, resulting in ["red", "blue", "green"].
If you use $addToSet to add a value that is already in the array, what happens?
Think about the meaning of 'set' in $addToSet.
$addToSet ensures that the value is only added if it does not already exist in the array. If the value is present, the array stays the same without duplicates.
You want to add the values "yellow" and "purple" to the colors array, ensuring no duplicates. Which query is correct?
To add multiple values uniquely, you need a special operator inside $addToSet.
The $each operator inside $addToSet allows adding multiple values uniquely. Option C correctly uses $each. Option C tries to add an array as a single element. Option C uses $push which can add duplicates. Option C uses a non-existent operator $all.
Given the document { _id: 1, items: ["apple", "banana"] }, you run this update:
{ $addToSet: { items: { name: "apple" } } }Why does the new value get added to the array?
Think about how MongoDB compares objects and strings in arrays.
The array contains the string "apple", but $addToSet is trying to add an object { name: "apple" }. MongoDB uses exact equality comparison (including type) for $addToSet, so the object differs from the string and is added to the array.
You have a collection where each document has an orders array of objects like { productId: 1, quantity: 2 }. You want to add a new order { productId: 3, quantity: 1 } only if it does not already exist (exact match). Which update query is the most efficient and correct?
Consider how $addToSet treats objects and the use of $each or $elemMatch.
Option A correctly uses $addToSet to add a single object if it does not exist exactly in the array. Option A uses $push which can add duplicates. Option A uses $each unnecessarily for a single object, but it still works. Option A uses $elemMatch which is not valid inside $addToSet. The most efficient and correct is option A.