Updating a Single Document with updateOne
In this step, you will learn how to modify a single document in a MongoDB collection. We will use the updateOne() method along with the $set operator to change a field's value in a specific document.
First, open the MongoDB Shell to interact with your database.
mongosh
Once inside the shell, switch to the mylab_database that was prepared for you.
use mylab_database
Let's view the current documents in the books collection. The .pretty() method formats the output to make it more readable.
db.books.find().pretty();
You should see the three initial book documents. The _id values will be unique in your environment.
[
{
_id: ObjectId("..."),
title: 'JavaScript Fundamentals',
author: 'Mike Johnson',
year: 2022,
pages: 350
},
{
_id: ObjectId("..."),
title: 'Python Deep Dive',
author: 'Sarah Williams',
year: 2021,
pages: 450
},
{
_id: ObjectId("..."),
title: 'Machine Learning Basics',
author: 'John Doe',
year: 2020,
price: 39.99
}
]
Now, let's update the publication year of the "JavaScript Fundamentals" book to 2023.
db.books.updateOne(
{ title: "JavaScript Fundamentals" },
{ $set: { year: 2023 } }
);
Let's break down this command:
updateOne(): This method finds the first document that matches the filter and updates it.
{ title: "JavaScript Fundamentals" }: This is the filter document. It tells MongoDB to find a document where the title field is "JavaScript Fundamentals".
{ $set: { year: 2023 } }: This is the update document. The $set operator replaces the value of the year field with 2023.
The command returns a result object that confirms the operation.
{
"acknowledged": true,
"insertedId": null,
"matchedCount": 1,
"modifiedCount": 1,
"upsertedCount": 0
}
The matchedCount: 1 shows that one document matched our filter, and modifiedCount: 1 shows that one document was successfully updated.
To verify the change, find the document again.
db.books.findOne({ title: "JavaScript Fundamentals" });
The output will show the updated document with the new year.
{
_id: ObjectId("..."),
title: 'JavaScript Fundamentals',
author: 'Mike Johnson',
year: 2023,
pages: 350
}