Update All Elements in a MongoDB Array Using $[] Positional Operator
📖 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 rating and a comment. You want to update all reviews to increase their rating by 1 point.
🎯 Goal: Build a MongoDB update query that uses the $[] all positional operator to increment the rating field of every review in the reviews array for a specific book.
📋 What You'll Learn
Create a collection named
books with one document containing a title and a reviews array with exactly two review objects.Define a filter variable
filter to select the book with the exact title 'Learn MongoDB'.Write an update query using
$inc and the $[] all positional operator to increment the rating of all reviews by 1.Complete the update command by combining the filter and update variables in a
db.books.updateOne() call.💡 Why This Matters
🌍 Real World
Updating all elements in an array field is common when you want to apply the same change to every item, such as increasing ratings, marking all tasks as done, or resetting flags.
💼 Career
Knowing how to use the $[] positional operator is important for database developers and administrators working with MongoDB to efficiently update array data without multiple queries.
Progress0 / 4 steps