MongoDB's updateOne()
method provides a powerful way to update a single document in a collection based on specified criteria. This method is particularly useful when Accuracy is needed in modifying specific documents without affecting others.
In this article, We will learn about MongoDB’s updateOne() method, including its syntax, best practices, examples, and how it differs from other update methods.
What is MongoDB updateOne() Method?MongoDB updateOne() is a method used to update a single document that matches a specified filter. We can target and update exactly one document that matches our filter criteria. It Compared to methods such as updateMany()
which updates multiple documents at once updateOne()
is more efficient when we only need to update a single document. When dealing with concurrent updates the updateOne()
helps maintain data consistency by focusing updates on a single document at a time.
Syntax
Parameters:db.collection.updateOne(<filter>, <update>, {
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [<filterdocument1>, ...],
hint: <document|string> // Available starting in MongoDB 4.2.1
})
This method returns a document that contains the following fields:
To better understand how the updateOne() method works, let's explore some practical examples using a students collection. In the following examples, we are working with:
Update the age of the student whose name is Annu
Query:
db.student.updateOne({name: "Annu"}, {$set:{age:25}})
Output:
Explanation: Here, the first parameter is the document whose value is to be changed i.e. {name:”Annu”} and the second parameter is the set keyword means to set(update) the following first matched key value with the older key value, i.e., from 20 to 25.
Example 2: Update a String Value in the DocumentUpdate the name of the first matched document whose name is Bhannu to Babita. Here, the value of the key must be of the same data type that was defined in the collection.
Query:
db.student.updateOne({name:"Bhannu"},{$set:{name:"Babita"}})
Output:
Explanation: Here, the first parameter is the document whose value is to be changed {name:”Bhannu”} and the second parameter is the set keyword means to set(update) the following first matched key value with the older key value.
Example 3: Insert a new field in the documentAdd a new field named class with the value 3
to the document where the student’s name is Bhannu.
Query:
db.student.updateOne({name: "Bhannu"}, {$set:{class: 3}})
Output
Explanation: Here, a new field is added, i.e., class: 3 in the document of a student whose name is Bhannu.
Example 4: Update using Update Operator ExpressionsLet's Updating all documents where name
is "Bhannu" to set age
to 25:
Query:
// Update all documents where name is "Bhannu" to set age to 25
db.student.updateMany(
{ name: "Bhannu" },
{ $set: { age: 25 } }
);
Output:
{Example 5: Update with Aggregation Pipeline
"_id" : ObjectId("600e9afd0cf217478ba93566"),
"name" : "Annu",
"age" : 20
}
{
"_id" : ObjectId("600e9afd0cf217478ba93567"),
"name" : "Bhannu",
"age" : 25
}
{
"_id" : ObjectId("600e9afd0cf217478ba93568"),
"name" : "Bhannu",
"age" : 25
}
Incrementing the age of all documents by 1 where name
is "Bhannu" using the aggregation pipeline:
Query:
// Increment the age of all documents by 1 where name is "Bhannu"
db.student.updateMany(
{ name: "Bhannu" },
[
{ $set: { age: { $add: ["$age", 1] } } }
]
);
Output:
{Example 6: Update with Upsert
"_id" : ObjectId("600e9afd0cf217478ba93566"),
"name" : "Annu",
"age" : 20
}
{
"_id" : ObjectId("600e9afd0cf217478ba93567"),
"name" : "Bhannu",
"age" : 26
}
{
"_id" : ObjectId("600e9afd0cf217478ba93568"),
"name" : "Bhannu",
"age" : 26
}
Updating the document with name
"Charlie" if it exists; otherwise, inserting a new document with name
"Charlie" and age
28:
Query:
// Update the document with name "Charlie" if it exists; otherwise, insert a new document
db.student.updateOne(
{ name: "Charlie" },
{ $set: { age: 28 } },
{ upsert: true }
);
Output:
{Best Practices for MongoDB updateOne()
"_id" : ObjectId("600e9afd0cf217478ba93566"),
"name" : "Annu",
"age" : 20
}
{
"_id" : ObjectId("600e9afd0cf217478ba93567"),
"name" : "Bhannu",
"age" : 26
}
{
"_id" : ObjectId("600e9afd0cf217478ba93568"),
"name" : "Bhannu",
"age" : 26
}
{
"_id" : ObjectId("600e9b3e0cf217478ba93569"),
"name" : "Charlie",
"age" : 28
}
To ensure efficient and error-free updates, here are a few best practices:
upsert
carefully, especially in production environments, to prevent unintentional insertions.hint
parameter for queries that require specific indexes.The MongoDB updateOne() method is ideal for scenarios where we need to modify a single document based on specific criteria. Whether we are updating fields, inserting new data, or using aggregation pipelines, updateOne()
offers precision, efficiency, and data integrity. By mastering this method, we can perform targeted updates in MongoDB with minimal overhead. This method ensures that our applications maintain optimal performance and data consistency with minimal effor
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4