0
0
MongoDBquery~30 mins

Array update with $[identifier] filtered in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Update Specific Items in a MongoDB Array Using $[identifier]
📖 Scenario: You manage a MongoDB collection that stores information about books in a library. Each book document contains an array of reviews, where each review has a reviewer name and a rating score.Sometimes, you need to update the rating given by a specific reviewer without changing other reviews.
🎯 Goal: Learn how to update only the reviews in the reviews array where the reviewer matches a specific name, using the $[identifier] filtered positional operator in MongoDB.
📋 What You'll Learn
Create a MongoDB document with a reviews array containing multiple review objects.
Define an array filter to target reviews by a specific reviewer name.
Use the $[identifier] filtered positional operator to update only the matching review's rating.
Complete the update operation with the correct filter and update syntax.
💡 Why This Matters
🌍 Real World
Updating specific items in arrays is common in applications like product reviews, user comments, or order items where only certain entries need changes without affecting others.
💼 Career
Knowing how to use array filters and the $[identifier] operator is essential for backend developers and database administrators working with MongoDB to write efficient and precise update queries.
Progress0 / 4 steps
1
Create a book document with a reviews array
Create a MongoDB document called book with the following fields: title set to "Learn MongoDB", and reviews as an array containing these objects exactly: { reviewer: "Alice", rating: 4 }, { reviewer: "Bob", rating: 5 }, and { reviewer: "Charlie", rating: 3 }.
MongoDB
Need a hint?

Define a constant book with the exact structure and values for title and reviews.

2
Define an array filter to target Bob's review
Create a variable called arrayFilters that is an array containing one filter object. This filter object should use the identifier elem and match reviews where elem.reviewer equals "Bob".
MongoDB
Need a hint?

Use const arrayFilters = [{ "elem.reviewer": "Bob" }]; to define the filter.

3
Write the update command using $[elem] to change Bob's rating
Write a MongoDB update command called updateCommand that uses $set to change reviews.$[elem].rating to 10. Use the arrayFilters variable you defined earlier in the update options.
MongoDB
Need a hint?

Use $set with the path reviews.$[elem].rating to update the rating.

4
Combine filter, update, and arrayFilters in the final update operation
Write a variable called finalUpdate that is an object containing these keys: filter to find the book by title "Learn MongoDB", update set to updateCommand, and options set to an object with arrayFilters equal to the arrayFilters variable.
MongoDB
Need a hint?

Combine the filter, update, and options with arrayFilters into one object called finalUpdate.