0
0
MongoDBquery~30 mins

Why updating documents matters in MongoDB - See It in Action

Choose your learning style9 modes available
Why Updating Documents Matters in MongoDB
📖 Scenario: You are managing a small online bookstore database using MongoDB. You have a collection of books, and sometimes you need to update the information about a book, like its price or stock quantity, to keep the data accurate and useful for customers.
🎯 Goal: Learn how to update documents in a MongoDB collection to keep your data current and correct.
📋 What You'll Learn
Create a collection called books with three book documents
Add a variable to specify the book to update
Write an update query to change the price of the specified book
Add a final query to confirm the update was successful
💡 Why This Matters
🌍 Real World
Updating documents keeps your database accurate, which is important for online stores, inventory systems, and any app that changes data over time.
💼 Career
Database administrators and backend developers often update documents to reflect real-world changes, such as price changes, stock updates, or user information edits.
Progress0 / 4 steps
1
Create the books collection with initial documents
Create a books collection with these exact three documents: { title: "The Great Gatsby", author: "F. Scott Fitzgerald", price: 10, stock: 5 }, { title: "1984", author: "George Orwell", price: 15, stock: 8 }, and { title: "To Kill a Mockingbird", author: "Harper Lee", price: 12, stock: 7 }.
MongoDB
Need a hint?

Use db.books.insertMany() with an array of objects to add multiple documents at once.

2
Specify the book to update
Create a variable called bookToUpdate and set it to { title: "1984" } to select the book you want to update.
MongoDB
Need a hint?

Use const bookToUpdate = { title: "1984" } to create the variable.

3
Update the price of the selected book
Write an update query using db.books.updateOne() to change the price of the book selected by bookToUpdate to 18.
MongoDB
Need a hint?

Use db.books.updateOne(bookToUpdate, { $set: { price: 18 } }) to update the price.

4
Confirm the update by finding the updated document
Write a query using db.books.findOne() with bookToUpdate to retrieve the updated book document.
MongoDB
Need a hint?

Use const updatedBook = db.books.findOne(bookToUpdate) to get the updated document.