0
0
MongoDBquery~30 mins

$addToSet for unique array additions in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$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
Need a 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
Need a 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
Need a 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
Need a hint?

Use db.users.findOne() with the filter { name: 'John' } to get the updated document.