$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