0
0
MongoDBquery~30 mins

Array update with positional $ operator in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Update a Specific Array Element Using the Positional $ Operator in MongoDB
📖 Scenario: You are managing a database for a small bookstore. Each book document contains an array of reviews. You want to update a specific review's rating based on the reviewer's name.
🎯 Goal: Learn how to update a specific element inside an array in a MongoDB document using the positional $ operator.
📋 What You'll Learn
Create a collection called books with one document containing a title and an array called reviews.
Add a variable to specify the reviewer's name whose rating you want to update.
Write a MongoDB update query that uses the positional $ operator to update the rating of the review by the specified reviewer.
Complete the update operation by specifying the correct filter and update syntax.
💡 Why This Matters
🌍 Real World
Updating specific elements inside arrays is common in applications like product reviews, user comments, or order items where you want to change only one item without replacing the whole array.
💼 Career
Knowing how to use the positional $ operator is essential for database developers and backend engineers working with MongoDB to efficiently update array elements.
Progress0 / 4 steps
1
Create the books collection with one book document
Create a MongoDB document for the books collection with the title set to 'Learn MongoDB' and a reviews array containing two review objects: { reviewer: 'Alice', rating: 4 } and { reviewer: 'Bob', rating: 5 }.
MongoDB
Need a hint?

Use db.books.insertOne() to add a document with the specified title and reviews array.

2
Set the reviewer's name to update
Create a variable called reviewerName and set it to 'Alice' to specify which reviewer's rating you want to update.
MongoDB
Need a hint?

Use const reviewerName = 'Alice' to store the reviewer's name.

3
Write the update query using the positional $ operator
Write a MongoDB update query using db.books.updateOne() that finds the document where reviews.reviewer matches reviewerName and updates the rating of that review to 5 using the positional $ operator.
MongoDB
Need a hint?

Use db.books.updateOne() with a filter on 'reviews.reviewer' and update 'reviews.$.rating' to 5.

4
Complete the update operation with correct filter and update syntax
Ensure the update query uses the correct filter { 'reviews.reviewer': reviewerName } and the update document { $set: { 'reviews.$.rating': 5 } } to update the rating of the matched review.
MongoDB
Need a hint?

Double-check the filter and update document syntax matches exactly.