0
0
MongoDBquery~5 mins

$addToSet for unique array additions in MongoDB - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the $addToSet operator do in MongoDB?

$addToSet adds a value to an array only if the value is not already present, ensuring unique elements.

Click to reveal answer
beginner
How is $addToSet different from $push in MongoDB?

$push adds values to an array regardless of duplicates, while $addToSet adds only if the value is not already in the array.

Click to reveal answer
beginner
Write a MongoDB update query snippet to add the value "apple" uniquely to the fruits array.
{ $addToSet: { fruits: "apple" } }
Click to reveal answer
intermediate
Can $addToSet add multiple unique values at once? If yes, how?

Yes, by using $each inside $addToSet to add multiple unique values.

{ $addToSet: { fruits: { $each: ["apple", "banana"] } } }
Click to reveal answer
intermediate
What happens if you use $addToSet on a field that is not an array?

If the field does not exist, MongoDB creates an array with the value. If the field exists and holds a non-array value, the update operation fails and MongoDB returns an error.

Click to reveal answer
What does $addToSet ensure when adding elements to an array?
ANo duplicate elements are added
BElements are always added at the start
CElements are removed if they exist
DArray is replaced completely
Which operator would add duplicates to an array in MongoDB?
A$push
B$addToSet
C$set
D$unset
How do you add multiple unique values to an array using $addToSet?
AUse <code>$push</code> with an array
BUse multiple <code>$addToSet</code> operators
CUse <code>$each</code> inside <code>$addToSet</code>
DUse <code>$set</code> with an array
If the target field does not exist, what does $addToSet do?
AThrows an error
BCreates the field as a string
CIgnores the update
DCreates the field as an array with the value
Which of these is a valid use of $addToSet?
A{ $addToSet: { tags: "mongodb" } }
B{ $addToSet: { tags: { $each: ["mongodb", "database"] } } }
C{ $addToSet: { tags: { $each: "mongodb" } } }
D{ $addToSet: { tags: ["mongodb", "database"] } }
Explain how $addToSet helps maintain unique elements in a MongoDB array.
Think about how sets work in real life, like a collection of unique stickers.
You got /4 concepts.
    Describe the difference between $addToSet and $push when updating arrays in MongoDB.
    Imagine adding items to a shopping list with or without checking if they are already there.
    You got /4 concepts.