MongoDB Update Document using update(), updateOne(), and updateMany()
You can update one or more fields in documents of a MongoDB collection based on a specific criteria. In older Mongo shell examples, this is commonly shown with the update() method. In current MongoDB usage, updateOne() and updateMany() are usually clearer because the method name states whether one document or many documents will be updated.
MongoDB Update Document – In this tutorial, we shall learn how to update MongoDB Documents based on a selection criteria using update() method. We shall also see how the same update can be written with updateOne() and updateMany() for modern MongoDB examples.
Syntax of MongoDB update() method for updating documents
The syntax of update() method is
db.collection_name.update(criteria, update, options)
where
| collection_name | Name of the collection in which you update document |
| criteria | [mandatory] Criteria to select documents for update |
| update | [mandatory] Updates to the fields for the selected documents |
The criteria document works like a filter. Only documents that match this filter are selected for update. The update document may use update operators such as $set, $unset, $inc, and $rename. If you pass a plain document without update operators, MongoDB treats it as a replacement document, so fields not present in the replacement document can be removed from the stored document.
MongoDB update() options: upsert, multi, collation, and writeConcern
Options – All options below are optional.
| Option | [Type][DefaultValue] DefaultAction | Description |
| upsert | [boolean][false] Does not insert a new document when no match found | If set to true, Inserts as a new document when no match is found for the criteria. |
| multi | [boolean][false] Updates only one document. | If set to true, updates all the documents that obey the criteria. |
| collation | [document][default] Uses binary comparison for comparing strings. | You may specify language-specific rules. Refer Collation. You can specify only only language in a Collation. |
| WriteConcern | [document][default] Refer Write Concern. | Write concern describes the level of acknowledgement requested from MongoDB. |
For new examples, it is often simpler to use the more explicit methods shown below.
db.collection_name.updateOne(filter, update, options)
db.collection_name.updateMany(filter, update, options)
| Method | Update scope | Typical use |
|---|---|---|
update() | One document by default, or many with { multi: true } | Older shell examples and legacy code |
updateOne() | First matching document only | When exactly one matching document should be changed |
updateMany() | All matching documents | When every document matching the filter should be changed |
replaceOne() | First matching document only | When the whole document should be replaced except _id |
Steps to update a MongoDB document safely
To update a MongoDB Document, follow the step by step guide below :
- Prepare a Criteria to select those documents for update.
criteria = {field1:value1, field2:value2,..} - Prepare Update Document.
update = {field1:value1, field2:value2,..} - [Optional] Query the Documents based on the Criteria formed to cross verify if you want to update all those selected Documents.
db.collection.find(criteria) - Prepare the options based on your use case.
- Run db.collection.update() method with criteria, update and options.
db.collection.update(criteria, update, options)
For field-level changes, prefer an update operator such as $set. This updates only the mentioned fields and keeps the other fields in the document unchanged.
db.people.updateOne(
{ name: "Manju" },
{ $set: { age: 28, place: "Vizag" } }
)
Example 1 – Update single MongoDB Document
Following is an example to update only one Document.
We shall use following people Collection in this Document Update Example and run the commands in Mongo Shell.
> db.people.find({})
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb2"), "name" : "Midhuna", "age" : 23, "place" : "Amaravati" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb3"), "name" : "Akhil", "age" : 24, "place" : "New York" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb4"), "name" : "Honey", "age" : 27, "profession" : "Docter" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb5"), "name" : "Manju", "age" : 23, "place" : "Amaravati", "profession" : "Carpenter" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb6"), "name" : "Bharat", "age" : 24, "place" : "New York", "profession" : "Scientiest" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb7"), "name" : "Arya", "age" : 25, "profession" : "Teacher" }
Now, prepare a criteria to select a document.
> criteria={name:"Manju"}
{ "name" : "Manju" }
Verify the documents you select with the criteria
> db.people.find(criteria)
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb5"), "name" : "Manju", "age" : 23, "place" : "Amaravati", "profession" : "Carpenter" }
We shall prepare the update document as below
> update={name:"Manju",age:28,place:"Vizag"}
{ "name" : "Manju", "age" : 28, "place" : "Vizag" }
To update only the values you want to change, rather than mentioning all the values once again, use $set command. Next example demonstrates the usage of $set command.
Let the Options have their default value.
And execute the update command on the Collection.
> db.people.update(criteria,update)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
MongoDB has acknowledged that “nMatched” : 1 there has been one Document that matched the Criteria, and “nModified” : 1 has modified one document.
Verify the update by querying the collection with the criteria
> db.people.find(criteria)
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb5"), "name" : "Manju", "age" : 28, "place" : "Vizag" }
The details have been updated successfully.
Notice that the profession field is not present after this update. That happened because the update document was a replacement document, not a $set update. This is useful only when you intentionally want to replace the matched document with a new document structure.
Update one MongoDB document with $set instead of replacing the document
To update selected fields while keeping the remaining fields unchanged, use $set. The following command changes only age and place.
db.people.updateOne(
{ name: "Manju" },
{ $set: { age: 28, place: "Vizag" } }
)
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
After this type of update, fields such as profession remain in the document unless you explicitly remove them with an operator such as $unset.
Example 2 – Update multiple MongoDB Documents
In this example, we shall update multiple mongodb documents with the help of $set command in update document and option multi set to true.
We shall use following people Collection in this Document Update Example and run the commands in Mongo Shell.
> db.people.find({})
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb2"), "name" : "Midhuna", "age" : 23, "place" : "Amaravati" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb3"), "name" : "Akhil", "age" : 24, "place" : "New York" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb4"), "name" : "Honey", "age" : 27, "profession" : "Docter" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb5"), "name" : "Manju", "age" : 28, "place" : "Vizag", "profession" : "Driver" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb6"), "name" : "Bharat", "age" : 24, "place" : "New York", "profession" : "Programmer" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb7"), "name" : "Arya", "age" : 25, "profession" : "Teacher" }
Now, prepare a criteria to select multiple MongoDB documents.
> criteria={place:"New York"}
{ "place" : "New York" }
> db.people.find(criteria).count()
2
There are multiple documents selected for the criteria.
We shall prepare the update document as below, including $set command
> update={$set:{bonus:250}}
{ "$set" : { "bonus" : 250 } }
To update only the values you want to change, rather than mentioning all the values once again, we used $set command.
We shall set multi option to true to update multiple MongoDB documents
> options={multi:true}
{ "multi" : true }
And execute the update command on the Collection.
> db.people.update(criteria,update,options)
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
MongoDB has acknowledged that “nMatched” : 2 there has been two documents that matched the criteria, and “nModified” : 2 has modified all the documents that matched the criteria.
Verify the update by querying the document with the criteria
> db.people.find(criteria)
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb3"), "name" : "Akhil", "age" : 24, "place" : "New York", "bonus" : 250 }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb6"), "name" : "Bharat", "age" : 24, "place" : "New York", "profession" : "Programmer", "bonus" : 250 }
The details have been updated successfully.
Update many MongoDB documents with updateMany()
The same multiple-document update can be written more directly with updateMany(). This avoids the need for the multi: true option.
db.people.updateMany(
{ place: "New York" },
{ $set: { bonus: 250 } }
)
{
acknowledged: true,
insertedId: null,
matchedCount: 2,
modifiedCount: 2,
upsertedCount: 0
}
MongoDB update operators for changing fields without replacing documents
Update operators define the exact change to make. They are safer for normal field updates because they do not replace the whole document.
| Update operator | Purpose | Example use |
|---|---|---|
$set | Sets or updates the value of a field | { $set: { place: "Vizag" } } |
$unset | Removes a field from a document | { $unset: { bonus: "" } } |
$inc | Increments a numeric field | { $inc: { age: 1 } } |
$rename | Renames a field | { $rename: { place: "city" } } |
The following example increments the age field by 1 for one matching document.
db.people.updateOne(
{ name: "Arya" },
{ $inc: { age: 1 } }
)
The following example removes the bonus field from all people in New York.
db.people.updateMany(
{ place: "New York" },
{ $unset: { bonus: "" } }
)
MongoDB upsert example with updateOne()
An upsert updates a matching document if one exists. If no matching document is found, MongoDB inserts a new document using the filter and update information.
db.people.updateOne(
{ name: "Sravani" },
{ $set: { age: 26, place: "Hyderabad", profession: "Designer" } },
{ upsert: true }
)
Use upsert: true carefully. It is useful when a record should exist after the operation, but the filter must be specific enough to avoid inserting an unintended duplicate.
Replace a MongoDB document when the whole document must change
If your intention is to replace the whole matched document, use replaceOne(). This makes the intent clearer than passing a plain replacement document to update().
db.people.replaceOne(
{ name: "Manju" },
{ name: "Manju", age: 28, place: "Vizag" }
)
The _id field is preserved, but other fields not present in the replacement document are removed. Use replaceOne() only when replacing the full document is the desired result.
Common mistakes when updating MongoDB documents
- Do not forget update operators such as
$setwhen you only want to change selected fields. - Check the filter with
find()before running an update that may affect many documents. - Use
updateMany()or{ multi: true }only when all matching documents should be changed. - Use
replaceOne()when replacing the full document is intentional. - Make
upsertfilters specific enough so that a missing match does not create the wrong document.
MongoDB update document FAQ
How do you update a document in MongoDB?
Use updateOne() to update one matching document, or use updateMany() to update all matching documents. For example, db.people.updateOne({ name: "Manju" }, { $set: { place: "Vizag" } }) updates the place field for one matching document.
How do you update multiple MongoDB documents with one command?
Use updateMany(filter, update). In older update() examples, use the option { multi: true }. For example, db.people.updateMany({ place: "New York" }, { $set: { bonus: 250 } }) updates every matching document.
What is the difference between updateOne() and updateMany() in MongoDB?
updateOne() updates the first document that matches the filter. updateMany() updates all documents that match the filter.
Why should $set be used while updating MongoDB fields?
$set updates only the fields mentioned in the update document and keeps the remaining fields unchanged. Without an update operator, a plain document can be treated as a replacement document.
What does upsert mean in a MongoDB update?
An upsert updates a matching document if one exists. If no document matches the filter, MongoDB inserts a new document when the option { upsert: true } is used.
Editorial QA checklist for MongoDB update document examples
- Confirm whether each example is intended to update one document, update many documents, or replace a whole document.
- Check that field-level updates use operators such as
$set,$unset, or$inc. - Verify that examples using
update()explain the effect of themultioption. - Make sure replacement examples warn that fields not included in the replacement document can be removed.
- Check that the verification query after each update matches the same filter used in the update command.
Conclusion: updating MongoDB documents with the right update method
In this MongoDB Tutorial – MongoDB Update Document, we have learnt to update single or multiple MongoDB documents using update() method and $set command with the help of examples. For current MongoDB code, use updateOne() when one document should change, updateMany() when all matching documents should change, and replaceOne() when the full document should be replaced.
TutorialKart.com