0
0
MongoDBquery~30 mins

updateOne method in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the updateOne Method in MongoDB
📖 Scenario: You are managing a small library database. Each book has a title, author, and a status indicating if it is available or checked out.
🎯 Goal: Learn how to update a single document in a MongoDB collection using the updateOne method.
📋 What You'll Learn
Create a collection named books with three book documents.
Define a filter to find a book by its title.
Use the updateOne method to change the status of the book.
Confirm the update by including the update operation in the code.
💡 Why This Matters
🌍 Real World
Updating records in a database is common in real-world apps like libraries, stores, or user management systems.
💼 Career
Knowing how to update documents in MongoDB is essential for backend developers and database administrators.
Progress0 / 4 steps
1
Create the books collection with initial documents
Create a variable called books that represents a MongoDB collection. Insert these three documents exactly: { title: 'The Hobbit', author: 'J.R.R. Tolkien', status: 'available' }, { title: '1984', author: 'George Orwell', status: 'available' }, and { title: 'To Kill a Mockingbird', author: 'Harper Lee', status: 'checked out' }.
MongoDB
Need a hint?

Use db.collection('books') to get the collection and insertMany to add documents.

2
Define a filter to find the book titled '1984'
Create a variable called filter and set it to an object that finds the book with the title exactly equal to '1984'.
MongoDB
Need a hint?

The filter is an object with the key title and value '1984'.

3
Use updateOne to change the status of '1984' to 'checked out'
Use the updateOne method on books with the filter variable and an update object that sets the status field to 'checked out'. Store the result in a variable called result.
MongoDB
Need a hint?

Use $set inside the update object to change the status field.

4
Complete the update operation by checking the modified count
Add a line that creates a variable called updatedCount and sets it to result.modifiedCount to know how many documents were updated.
MongoDB
Need a hint?

The modifiedCount property tells how many documents were changed.