Open In App

MongoDB – updateOne() Method

Last Updated : 28 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Key Benefits of updateOne() Method:

  • This method can accept a document that only holds update operator expressions.
  • This method can also accept aggregation pipelines.
  • In this method, if the value of upsert is set to true for the shard collection, then we must include the full shard key in the filter/selection criteria. Or if the value of upsert is not set to true, then we must include an exact match on the _id field.
  • The update operation will fail if this operation changes the size of the document.
  • We can also use this method inside multi-document transactions.

Syntax

db.collection.updateOne(<filter>, <update>, {
   upsert: <boolean>,
   writeConcern: <document>,
   collation: <document>,
   arrayFilters: [<filterdocument1>, …],
   hint: <document|string> // Available starting in MongoDB 4.2.1
})

Parameters:

  • <filter>: Specifies the selection criteria for the update.
  • <update>: A document or pipeline containing modifications to apply.

Optional Parameters:

  • upsert: The default value of this parameter is false. When it is true it will make a new document in the collection when no document matches the given condition in the update method.
  • writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
  • collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
  • arrayFilters: It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array.
  • hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error.

Return:

This method returns a document that contains the following fields:

  • nMatched: This field contains the number of matched documents.
  • modifiedCount: This field contains the number of modified documents.
  • upsertedId: This field contains the _id for the upserted document.
  • acknowledged: The value of this field is true if write concern was enabled or false if write concern was disabled.

Examples of MongoDB updateOne() Method

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:

  • Database: gfg
  • Collection: student
  • Document: Four documents contains name and age of the students

Example 1: Update an Integer Value in the Document

Update the age of the student whose name is Annu

Query:

db.student.updateOne({name: "Annu"}, {$set:{age:25}})

Output:

update the age of the student whose name is annu example 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 Document

Update 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:

example 2 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 document

Add 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 Expressions

Let’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:

{
"_id" : ObjectId("600e9afd0cf217478ba93566"),
"name" : "Annu",
"age" : 20
}
{
"_id" : ObjectId("600e9afd0cf217478ba93567"),
"name" : "Bhannu",
"age" : 25
}
{
"_id" : ObjectId("600e9afd0cf217478ba93568"),
"name" : "Bhannu",
"age" : 25
}

Example 5: Update with Aggregation Pipeline

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:

{
"_id" : ObjectId("600e9afd0cf217478ba93566"),
"name" : "Annu",
"age" : 20
}
{
"_id" : ObjectId("600e9afd0cf217478ba93567"),
"name" : "Bhannu",
"age" : 26
}
{
"_id" : ObjectId("600e9afd0cf217478ba93568"),
"name" : "Bhannu",
"age" : 26
}

Example 6: Update with Upsert

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:

{
"_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
}

Best Practices for MongoDB updateOne()

To ensure efficient and error-free updates, here are a few best practices:

  1. Use indexes: When using filters, make sure relevant fields are indexed for faster lookup.
  2. Test with a small dataset: When using aggregation pipelines, first test on smaller data before applying it to large datasets.
  3. Ensure data integrity: Use upsert carefully, especially in production environments, to prevent unintentional insertions.
  4. Use write concern: Set appropriate write concern for critical operations to ensure data durability.
  5. Monitor performance: Use the hint parameter for queries that require specific indexes.

Conclusion

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



Next Article

Similar Reads