0
0
MongoDBquery~30 mins

$set operator for setting fields in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$set Operator to Update User Profiles
📖 Scenario: You are managing a user database for a small online community. Each user has a profile stored as a document in a MongoDB collection called users. You want to update user profiles by changing or adding specific fields without replacing the entire document.
🎯 Goal: Learn how to use the MongoDB $set operator to update specific fields in user documents.
📋 What You'll Learn
Create a users collection with three user documents having fields _id, name, and age.
Define a filter to select a user by name.
Use the $set operator to update the age field of the selected user.
Add a new field email to the selected user using $set.
💡 Why This Matters
🌍 Real World
Updating user profiles is a common task in web applications where user information changes over time. Using the <code>$set</code> operator lets you change only the needed fields without affecting others.
💼 Career
Understanding how to update documents efficiently in MongoDB is essential for backend developers and database administrators working with NoSQL databases.
Progress0 / 4 steps
1
Create the users collection with initial user documents
Create a variable called users that is a list of three documents. Each document should have the exact fields and values: { _id: 1, name: "Alice", age: 25 }, { _id: 2, name: "Bob", age: 30 }, and { _id: 3, name: "Charlie", age: 35 }.
MongoDB
Need a hint?

Use an array with three objects. Each object must have _id, name, and age fields exactly as shown.

2
Define a filter to select the user named "Bob"
Create a variable called filter that is a document with the exact field name set to "Bob".
MongoDB
Need a hint?

The filter should be an object with name set to "Bob".

3
Use the $set operator to update Bob's age to 31
Create a variable called update that uses the $set operator to set the age field to 31.
MongoDB
Need a hint?

Use $set with an object that sets age to 31.

4
Add a new field email to Bob's profile using $set
Extend the update variable to also set the email field to "bob@example.com" using the $set operator.
MongoDB
Need a hint?

Add email: "bob@example.com" inside the $set object.