In this MongoDB tutorial, we are going to discuss “MongoDB update documents“. Here we will learn How to update documents into MongoDB. We will also cover this with different operations with examples. These are the following topics that we are going to cover in this tutorial:
- MongoDB update query
- MongoDB update _id Field
- MongoDB update operators
- MongoDB update documents
- MongoDB update all documents
- MongoDB update query with where clause
- MongoDB update multiple documents
- MongoDB update array elements
- MongoDB update nested array elements
- MongoDB update query with condition
- MongoDB update documents using compass
- MongoDB update if exists
- MongoDB update vs updateMany
- MongoDB update vs replace
- MongoDB update not working
- MongoDB update query with python
- MongoDB update document by id
- MongoDB update document by ObjectId
- MongoDB update document with new field
- MongoDB update document where
MongoDB update query
In MongoDB, we use the update() method to modify existing documents of a collection. Depending upon the update parameter, you can modify the specific fields of an existing document or replace the existing document.
Syntax:
Below syntax is used to update documents in MongoDB:
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>,
let: <document>
}
)
The update() method takes the following parameters:
| Parameters | Type | Description |
|---|---|---|
| query | document | Query selector for the update |
| update | document or pipeline | Modifications to apply like update documents, replacement document, and aggregation pipeline |
| upsert | boolean | (optional) When true: create a new document if no documents match the query. update a single query that matches the query. |
| multi | boolean | (optional) If true, then update multiple documents and if set false then update only one document. By default this is false. |
| writeConcern | document | It is used to write concerns with transactions. |
| collation | document | (optional) It allows users to language-specific rule string comparison. |
| arrayFilters | array | It is used to determine which array elements to modify for an update operation on the array field. |
| hint | document or string | It is used to take index specification documents or index name strings. |
| let | document | (optional) It is used to specify documents with a list of variables. |
This method returns a writeResult document that contains the status of the operations.
Read: How to drop a database in MongoDB
MongoDB update _id field
In MongoDB, you can’t directly update the _id field but by writing some script you can update the _id field. You will more understand with the help of examples so let’s understand the example.
Example:
In this example, I will show you how you can update the _id field.
These are some documents I have been inserted into the persons’ collection.
> db.persons.insertMany([
{"_id":ObjectId("612f146e1a18fbb8eaf2b8e2"), "Name":"David", "Age":22, "Gender":"Male" },
{"_id":ObjectId("612f147f1a18fbb8eaf2b8e3"), "Name":"Peter", "Age":24, "Gender":"Male" },
{"_id":ObjectId("612f14b21a18fbb8eaf2b8e4"), "Name":"Stromi", "Age":22, "Gender":"Female" },
{"_id":ObjectId("612f14b21a18fbb8eaf2b8e5"), "Name":"Kim", "Age":23, "Gender":"Female" }
])
After inserting the documents into the collection, see the documents using the MongoDB shell:

The following query is used to update the _id field in MongoDB
> var documents = db.persons.findOne({"Name": "Stromi"})
> document._id
ObjectId("612f14b21a18fbb8eaf2b8e4")
> document._id = 1001
1001
> db.perosns.insert(document)
WriteResult({ "nInserted" : 1 })
> db.persons.remove({_id: ObjectId("612f14b21a18fbb8eaf2b8e4")})
WriteResult({ "nRemoved" : 1 })
Here, we select the document that _id field we want to update by using the findOne() method and store it into a variable called document.
After we update the id by using “document._id = 1001″ and insert the updated document into the collection and we remove the previous document by using the remove() method.
Check the below snap to see the execution of code in MongoDB shell:

We successfully updated the _id field. Here, the find() method is used to check the documents of the collection.
Read: Export MongoDB to CSV
MongoDB update operators
In MongoDB, there are various operators available for update operations:
You need to specify the operators in the document form:
{
<operator1>: { <field1>: <value1>, ... },
<operator2>: { <field2>: <value2>, ... },
...
}
Update operators
Fields
| Name | Description |
|---|---|
| $currentDate | It is used to sets the value of a field to the current date, either as a date or timestamp. |
| $inc | By the specified amount increment the value of the field. |
| $min | The field value is less than the existing field value then update. |
| $max | The field value is greater than the existing field value then update. |
| $mul | By the specified amount multiplies the value of the field. |
| $rename | Used to rename a field. |
| $set | Used to set a value of a field in a document. |
| $setOnInsert | Set the value of a field if an update results in an insert of a document. |
| $unset | Remove the specified field from documents. |
Array operators
| Name | Description |
|---|---|
| $ | Placeholder to update the first element that matches the query condition. |
| $[] | Matches the query condition and update all the elements in an array. |
| $[<identifier>] | Use to update all the elements that match the arrayFilters condition. |
| $addToSet | If not exist in the set then add elements to an array. |
| $pop | Use to remove first or the last element of an array |
| $pull | Use to remove all the elements that match a specified query. |
| $push | use to add item into an array |
| $pullAll | Use to remove all the matching values from an array. |
Modifiers
| Name | Description |
|---|---|
| $each | It modifies the $push and $addToSet operators to append multiple items for array updates. |
| $position | To specify the position in the array modify the $push operator to add elements |
| $slice | It modifies the $push operator to limit the size of updated arrays. |
| $sort | It modifies the $push operator to reorder documents stored in an array. |
Bitwise
| Name | Description |
|---|---|
| $bit | It performs bitwise AND, OR, and XOR updates of integer values. |
In this topic, we covered all the update operations that are used in the MongoDB database.
Read: MongoDB is not recognized as an internal or external command
MongoDB update documents
In MongoDB, For update a single document within the collection we use the updateOne() method.
Example:
In this example, we use the aggregation pipeline to modify or update a field.
> db.group.insertMany([
{
"_id" : 1,
"member" : "abc123",
"status" : "A",
"points" : 2,
"misc1" : "note to self: confirm status",
"misc2" : "Need to activate",
"lastUpdate" : ISODate("2019-01-01T00:00:00Z")
},
{
"_id" : 2,
"member" : "xyz123",
"status" : "A",
"points" : 60,
"comments" : [
"reminder: ping me at 100pts",
"Some random comment"
],
"lastUpdate" : ISODate("2019-01-01T00:00:00.00Z")
}
])
The following documents will insert into the group collection. And you can check the documents of the group collection by using the find() method.

Here, these are some documents inserted into the group collection. Now, we apply the updateOne() method for update the documents.
> db.group.UpdateOne(
{ _id : 2},
[{ $set :
{ status : "Modified",
lastUpdate : "$$NOW"}}]
)
Here, we use an aggregation pipeline to modify a field. First, we select a particular field by using _id then apply the $set field to a set a value to status and lastUpdate field.
See the execution of the code in the MongoDB shell:

The find() method is used to check the documents of the collection. And see we successfully updated a document by using the updateOne() method.
Read: MongoDB join two collections
MongoDB update all documents
In MongoDB, To update all documents that match the specified filter update with the help of the updateMany() method.
Example:
In this example, I will show how you can use the updateMany() method to update all documents of the collection.
> db.items.insertMany([
{ "_id": 1, "item:: "almond", "description": "almond clusters", "instock": 120},
{ "_id": 2, "item:: "bread", "description": "raisin and nut bread", "instock": 80},
{ "_id": 3, "item:: "pecans", "description": "candied pecans", "instock": 60}
])
After inserting the documents, Check the documents of the items collection using the find() method

The following operation update all the documents of items collection where instock are greater than 70 and use $set to add a new field review where instock is greater than 70:
> db.items.updateMany(
{ instock : { $gt : 70}},
{ $set : {"Review" : true}}
)
See the execution of code in the MongoDB shell:

You can see that all the documents are updated successfully.
Read: Import CSV into MongoDB
MongoDB update query with where clause
We can do this with the help of pipeline operations. let’s understand with the help of examples
Example:
The following documents are inserted into students collections.
> db.students.insertMany([
{ "_id" : 1, "grades" : [ 95, 92, 90 ] },
{ "_id" : 2, "grades" : [ 98, 100, 102 ] },
{ "_id" : 3, "grades" : [ 95, 110, 100 ] }
])
Here, we update all the elements of the grades array where grades greater than or equal to 100. For updating this, we use operator $[<identifier>] with the arrayFilter:
> db.students.update(
{ grades: { $gte: 100 } },
{ $set: { "grades.$[element]" : 100 } },
{
multi: true,
arrayFilters: [ { "element": { $gte: 100 } } ]
}
)
After executing the above code, this will display the following output:
> db.students.find()

Here, we successfully updated all the grades that are greater than 100 using the arrayFilters parameter.
Read: MongoDB group by multiple fields
MongoDB update multiple documents
In MongoDB, you can update multiple documents by using a single method that is updateMany(). And here we use an aggregation pipeline that will update the documents.
Example:
In this example, we update the documents with the calculated grade average and letter grade using an aggregation pipeline.
> db.students.insert([
{"_id":1, "tests":[ 95, 92, 90 ], "lastUpdate":ISODate("2020-01-01T00:00:00Z")},
{"_id":2, "tests":[ 94, 88, 90 ], "lastUpdate":ISODate("2020-01-01T00:00:00Z")},
{"_id":3, "tests":[ 70, 75, 82 ], "lastUpdate":ISODate("2020-01-01T00:00:00Z") }
])
Here, see we inserted some documents into the students’ collection.

Now, we will update multiple documents using the aggregation pipeline.
> db.students.updateMany(
{ },
[
{$set:{ average:{ $trunc:[{ $avg:"$tests"}, 0]},lastUpdate: "$$NOW" } },
{$set:{ grade:{ $switch:{
branches: [
{case:{ $gte:["$average", 90 ] },then:"A"},
{case:{ $gte:["$average", 80 ] },then:"B"},
{case:{ $gte:["$average", 70 ] },then:"C"},
{case:{ $gte:["$average", 60 ] },then:"D"}
],
default: "F"
} } } }
]
)
Here, we use the updateMany() method to update multiple documents. And in this method:
- { } is used to apply condition on all the documents.
- Use the $set field to update the documents with average grades and letter grades.
Now see the execution of the code in the MongoDB shell:

We successfully updated all the documents of students collection. The find() method is used to check documents of the collection.
Read: MongoDB failed to connect
MongoDB update array elements
We can update the specific elements of an array of documents in MongoDB. To update the documents we use updateMany() method. You will more understand with the example so let’s get into it.
Example:
In this example, we will gonna do check the elements in the grades array if the grade is greater than equal to 85 then modify all the elements of the mean with 100.
> db.grades.insert([
{
"_id" : 1,
"grades" : [
{ "grade" : 80, "mean" : 75, "std" : 6 },
{ "grade" : 85, "mean" : 90, "std" : 4 },
{ "grade" : 85, "mean" : 85, "std" : 6 }
]
},
{
"_id" : 2,
"grades" : [
{ "grade" : 90, "mean" : 75, "std" : 6 },
{ "grade" : 87, "mean" : 90, "std" : 3 },
{ "grade" : 85, "mean" : 85, "std" : 4 }
]
}
])
These are some documents inserted into the grades collection.

Now, we modify the value of the mean-field for all the elements in the grades array where grades are greater than equal to 85.
For this, we use filtered positional operator $[<identifier>] with arrayFilters.
> db.grades.updateMany(
{ },
{ $set : { "grades.$[elem].mean" : 100 } },
{ arrayFilters : [{ "elem.grade" : { $gte : 85 } } ] }
)
See the execution of the code in the MongoDB shell:

Here, we are used the filtered positional operator and updated all mean fields where grades are greater than equal to 85.
Updated documents of grades collection:
> db.grades.find()
{
"_id" : 1,
"grades" : [
{ "grade" : 80, "mean" : 75, "std" : 6 },
{ "grade" : 85, "mean" : 100, "std" : 4 },
{ "grade" : 85, "mean" : 100, "std" : 6 }
]
}
{
"_id" : 2,
"grades" : [
{ "grade" : 90, "mean" : 100, "std" : 6 },
{ "grade" : 87, "mean" : 100, "std" : 3 },
{ "grade" : 85, "mean" : 100, "std" : 4 }
]
}
Here, we successfully updated specific array element documents. And try to do more examples so that you will understand how does MongoDB update the documents.
Read: MongoDB drop collection
MongoDB update nested array elements
In the topic, you will understand how you can update nested array elements and as you know in the previous topic, we also cover about update the array elements. These both topics little bit similar to each other.
Here, I’ll give a different example so that you can easily understand how to update nested array elements.
Example:
The following documents were inserted into student collection:
> db.student.insert([
{ "_id" : 1,
"grades" : [
{ type: "quiz", questions: [ 10, 8, 5 ] },
{ type: "quiz", questions: [ 8, 9, 6 ] },
{ type: "hw", questions: [ 5, 4, 3 ] },
{ type: "exam", questions: [ 25, 10, 23, 0 ] },
]
}
])
Now, we update the nested grades. questions array and by using the $inc operator to increment the value by 2 where values are greater than equal to 8.
> db.student.updateMany(
{},
{ $inc: { "grades.$[].questions.$[score]" : 2 } },
{ arrayFilters: [ { "score": { $gte: 8 } }]
})
The execution of the updateMany() method to update nested array elements:

We successfully updated the documents. Now check the documents of the student collection:
> db.student.find()
{ "_id" : 1,
"grades" : [
{ "type" : "quiz", "questions" : [ 12, 10, 5 ] },
{ "type" : "quiz", "questions" : [ 10, 11, 6 ] },
{ "type" : "hw", "questions" : [ 5, 4, 3 ] },
{ "type" : "exam", "questions" : [ 27, 12, 25, 0 ] }
] }
See all the fields are updated successfully and this way you can easily update the elements of the nested array. The find() method is used to retrieve the documents of the collection.
Read: How to store images in MongoDB
MongoDB update query with condition
In MongoDB, you can update the particular field with conditions by using the update() method.
Example:
To understand update query with a condition let’s understand this example
> db.data.insertMany([
{ "_id":1, "name":"Smith", "class":11, "subject":"Science/Maths" },
{ "_id":2, "name":"Tom", "class":12, "subject":"Arts" },
{ "_id":3, "name":"Adam", "class":12, "Branch":"Commerce/Maths" }
])
These are some documents inserted into the data collection.
Now, we apply the update() method with conditions so we use the $set field to update the field values of the documents.
> db.data.update(
{ name : "Tom" },
{ $set : {"subject" : "Commerce" }}
)
Here, we update the subject field value where the name is Tom. To check the updated document use the find() method.
See the execution of the code in MongoDB shell:

We successfully updated the subject field value. This way you can easily update the documents according to the condition.
Note that, If you have multiple fields with the same name then in that situation:
- Choose the unique field with that help you can easily update the field.
- You also know about the _id field as well that is always unique so with that help you can update the fields.
Read: MongoDB group by count
MongoDB update documents using compass
In MongoDB compass, you can not update multiple documents at a single time. Compass performs find one and update operation and update only those fields that you have changed. You can edit documents in List or Table view.
Procedure to update the document:
- Select the collection which documents you want to update.
- Select tab based on viewing documents in List, JSON, or Table view

Here, we selected the artists’ collection to update the document and select the VIEW in which you want to see the documents.
- To modify the document hover the doument and click on pencil icon.

- After click on the pencil icon document will open in edit mode

Here, you can make the changes to the fields and also change the data type of the values.
- You can also delete a field, click on X icon to the left side of the field.

- Once you selected the field for removal then it will appear in red.
- You can modify the existing field name or values and after update the field then it will display in yellow color.
- You can also add a new field in the documents after an existing field, row number in the dialog click on plus sign and set the datatype as per your requirement and after adding the field it will display in green color.
- when you finished editing the documents, click on the update button to make all the changes.
- To exit from the edit mode and cancel all the pending changes, click on the Cancel button.

This way you can simply update the document of the collection using MongoDB compass.
Read: Import JSON and insert JSON into MongoDB
MongoDB update if exists
To perform this task, we use an upsert operation. When you insert a value and the value already exists then an update would be performed and if that value does not exist then it gets inserted.
Example:
In this example, we cover if the document exists then update that otherwise insert it as a new field.
The following documents are inserted into the marks collection:
> db.marks.insertMany([
{ "_id": 1, "subject": "History", "score": 88 },
{ "_id": 2, "subject": "Science", "score": 92 },
{ "_id": 3, "subject": "Math", "score": 97 },
{ "_id": 4, "subject": "English", "score": 92 },
{ "_id": 5, "subject": "Hindi", "score": 69},
{ "_id": 6, "subject": "Social Science", "score": 80 }
])
After inserting the documents into collection check it by using the find() method in MongoDB shell:

Now, we take both cases to understand the concept of the update if exists:
Case 1: When the value you are inserting that already exists then the value gets updated by the following query:
> db.marks.update(
{ subject : "English" },
{ $set : { "score" : 88 }},
{ upsert : true }
)
Here, See the subject (English) that already exists in the documents so the update() method updates the score either inserting it as a new field.

See the documents of the marks collection value are successfully updated.
Case 2: When the value you are inserting does not already exist then the value is unique then it gets inserted by the following query:
> db.marks.update(
{ subject : "Computer" },
{ $set : { "_id" : 7, "score" : 73}},
{ upsert : true}
)
Here, see after using the update() method the field we are updating that does not exist so using upsert it will insert as a new field.

See we successfully inserted a new field because as per the condition the field does not exist in the marks collection.
Note, What is an upsert operation?
An upsert is an option that is used to update operations or in other words, upsert is a combination of update and insert (update + insert = upsert).
Read: MongoDB sort by date
MongoDB update vs updateMany
The “update” method is used to modify the specific fields of the existing document or replace existing documents depending on the update parameter whereas the “updateMany” is used to update all the documents that match the given filter.
Example:
Here I’ll give you examples of both the method update and updateMany.
The following documents are inserted into the inventory collection:
> db.inventory.insertMany([
{ "_id": 1, "item": "abc1", "description": "product 1", "qty": 300 },
{ "_id": 2, "item": "abc2", "description": "product 2", "qty": 200 },
{ "_id": 3, "item": "xyz1", "description": "product 3", "qty": 250 },
{ "_id": 4, "item": "VWZ1", "description": "product 4", "qty": 300 },
{ "_id": 5, "item": "VWZ2", "description": "product 5", "qty": 180 }
])
After inserting the documents, we will update documents by using the update() method:
> db.inventory.update(
{ "item" : "VWZ2"},
{ $set : { "qty" : 200}}
)
Check the execution of code in MongoDB shell:

Update documents by using the updateMany() method:
> db.inventory.updateMany(
{ "item" : "xyz1"},
{ $set : { "qty" : 250}}
)
Check the execution of code in MongoDB shell:

So we see both the example of updating the documents and successfully updating the documents.
Read: MongoDB sort by field
MongoDB update vs replace
In this topic, we discuss the update and replace method of MongoDB in detail:
The updateOne() method is used to update a single document. We replace an existing document or update specific fields in an existing document.
The replaceOne() method is used to replace the entire document field and your old data will replace by the new one.
Example:
In this example, you will see how you can use the updateOne() and replaceOne() method to update the documents.
Use of the replaceOne() method:
> db.test.insert( { "_id" : 123, "my_test" : 3333 })
> db.test.replaceOne( { "_id" : 123}, { "my_test" : 7})
Here, we only insert a single document into the test collection and after that apply the replaceOne() method to replace the old document.
See the execution of the code in MongoDB shell:

Use of the updateOne() method:
> db.test.updateOne( { "_id" : 123}, { "my_test1" : 7})
> db.test.find()
{ "_id" : 123, "my_test" : 5, "my_test1" : 7 }
Here, the updateOne() method updated the document in an existing document.
See the execution of the code in MongoDB shell: