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
$addToSet for unique array additions
📖 Scenario: You are managing a simple database of users and their favorite fruits. Each user has a list of fruits they like. You want to make sure that when you add a new fruit to a user's list, it only gets added if it is not already there, so the list stays unique.
🎯 Goal: Build a MongoDB update operation using $addToSet to add a fruit to a user's favorite fruits array only if it is not already present.
📋 What You'll Learn
Create a collection called users with one document for a user named John who has favorite fruits ['apple', 'banana'].
Define a variable newFruit with the value 'banana'.
Write an update query using $addToSet to add newFruit to John's favorite fruits array.
Add a final query to find and return John's document after the update.
💡 Why This Matters
🌍 Real World
Managing user preferences or tags in a database where duplicates should be avoided.
💼 Career
Understanding $addToSet is important for database developers and administrators to maintain clean and efficient data.
Progress0 / 4 steps
1
Create the initial user document
Insert a document into the users collection with name set to 'John' and favoriteFruits set to ['apple', 'banana'].
MongoDB
Hint
Use db.users.insertOne() to add the document.
2
Define the new fruit to add
Create a variable called newFruit and set it to the string 'banana'.
MongoDB
Hint
Use const newFruit = 'banana' to define the variable.
3
Update the user's favorite fruits using $addToSet
Write an update query using db.users.updateOne() to find the document where name is 'John' and use $addToSet to add newFruit to the favoriteFruits array.
MongoDB
Hint
Use db.users.updateOne() with a filter and $addToSet to add the fruit uniquely.
4
Retrieve the updated user document
Write a query using db.users.findOne() to find and return the document where name is 'John' after the update.
MongoDB
Hint
Use db.users.findOne() with the filter { name: 'John' } to get the updated document.
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
Step 1: Understand the purpose of $addToSet
$addToSet adds a value to an array only if that value is not already present, ensuring uniqueness.
Step 2: Compare with other array operations
Unlike operators that remove duplicates or replace arrays, $addToSet only adds unique values without duplicates.
Final Answer:
To add a value to an array only if it does not already exist -> Option D
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?
Step 1: Recall syntax for adding multiple unique values
To add multiple unique values with $addToSet, use $each inside it.
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.
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
Step 1: Understand $addToSet behavior with existing value
The value "blue" already exists in the array, so $addToSet will not add it again.
Step 2: Determine the resulting array
Since "blue" is present, the array remains unchanged as ["red", "blue"].
Final Answer:
["red", "blue"] -> Option B
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
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.
Step 2: Use $each to add multiple unique elements
Wrapping the array with $each inside $addToSet adds each element uniquely.
Final Answer:
Use $addToSet: { tags: { $each: ["nodejs", "mongodb"] } } -> Option A
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?