MongoDB Update Documents – Complete tutorial

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:

ParametersTypeDescription
querydocumentQuery selector for the update
updatedocument or pipelineModifications to apply like update documents, replacement document, and aggregation pipeline
upsertboolean(optional) When true:
create a new document if no documents match the query.
update a single query that matches the query.
multiboolean (optional) If true, then update multiple documents and if set false then update only one document. By default this is false.
writeConcerndocumentIt is used to write concerns with transactions.
collationdocument(optional) It allows users to language-specific rule string comparison.
arrayFiltersarrayIt is used to determine which array elements to modify for an update operation on the array field.
hintdocument or stringIt is used to take index specification documents or index name strings.
letdocument(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:

Update _id Field in MongoDB
Update _id Field in MongoDB

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:

MongoDB update _id field example
MongoDB update _id field

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

NameDescription
$currentDateIt is used to sets the value of a field to the current date, either as a date or timestamp.
$incBy the specified amount increment the value of the field.
$minThe field value is less than the existing field value then update.
$maxThe field value is greater than the existing field value then update.
$mulBy the specified amount multiplies the value of the field.
$renameUsed to rename a field.
$setUsed to set a value of a field in a document.
$setOnInsertSet the value of a field if an update results in an insert of a document.
$unsetRemove the specified field from documents.

Array operators

NameDescription
$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.
$addToSetIf not exist in the set then add elements to an array.
$popUse to remove first or the last element of an array
$pullUse to remove all the elements that match a specified query.
$pushuse to add item into an array
$pullAllUse to remove all the matching values from an array.

Modifiers

NameDescription
$eachIt modifies the $push and $addToSet operators to append multiple items for array updates.
$positionTo specify the position in the array modify the $push operator to add elements
$sliceIt modifies the $push operator to limit the size of updated arrays.
$sortIt modifies the $push operator to reorder documents stored in an array.

Bitwise

NameDescription
$bitIt 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.

MongoDB updateOne
documents in the group collection

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:

MongoDB updateOne example
use of updateOne() method

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

MongoDB updateMany
documents in the items collection

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:

MongoDB updateMany example
use of updateMany() method

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()
MongoDB update query with where clause
After the update the documents

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.

MongoDB update multiple documents
Insert documents into the 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:

MongoDB update multiple documents example
Update multiple documents

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.

MongoDB update array elements
Insert documents into the 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:

MongoDB update array elements example
MongoDB update array elements

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:

MongoDB update nested array elements
MongoDB 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:

MongoDB update query with condition
MongoDB update query with a condition

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
MongoDB update documents using compass
MongoDB update documents using compass

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.
update documents using compass
Edit Document
  • After click on the pencil icon document will open in edit mode
MongoDB compass update documents
MongoDB compass update documents

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.
update documents using compass example
Delete the document field in the compass
  • 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.
update documents in MongoDB compass
update documents in MongoDB Compass

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:

MongoDB update if exists
Documents of marks collection

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.

MongoDB update if value is already exists
MongoDB update if the value exists

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.

MongoDB update if exists example
MongoDB update if exists example

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:

MongoDB update vs updatemany
update document using update() method

Update documents by using the updateMany() method:

> db.inventory.updateMany(
     { "item" : "xyz1"},
     { $set : { "qty" : 250}}
)

Check the execution of code in MongoDB shell:

MongoDB update vs updateMany example
update documents using updateMany() method

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:

MongoDB update vs replace
use of replaceOne() method

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:

MongoDB update vs replace example
use of updateOne() method

Here, we learned both (update and replace) the methods of MongoDB.

Read: Create tables in MongoDB

MongoDB update not working

A few days back I was working with the MongoDB update method but not getting the result as per the requirement. Check the below script and see the update method not working properly.

The following documents were inserted into the movies collection.

> db.movies.insertMany([
{ "_id": 1, "name": "HarryPotter", "type": "fiction", "rating": "A" },
{ "_id": 2, "name": "LOTR", "type": "fiction", "rating": "D" },
{ "_id": 3, "name": "Witchcraft", "type": "horror", "rating": "A" },
{ "_id": 4, "name": "panda", "type": "romance", "rating": "A" },
{ "_id": 5, "name": "What is new", "type": "comedy", "rating": "A" }
{ "_id": 6, "name": "Date", "type": "romance", "rating": "D" }
])

After inserting the document into the collection check it by using the find() method in MongoDB Shell

MongoDB update not working
Insert documents in the collection

And after that try to update the documents but not get the output per the demand or update() method not working properly.

MongoDB update not working example
MongoDB update is not working

See the output after updating the documents, the update() method either updates a field, replace all fields where “_id: 2”.

So to resolve this error, I try to find the solution and read a lot of articles on the web. I found the solution and that’s works for me so I’m sharing it with you.

When you are updating any documents always use the updateOne() or updateMany() method because sometimes the update() method works as replace() method and this method either update, change all the fields of documents.

when you are updating documents of the collection use the $set operation to update the value of a particular field.

> db.movies.updateOne(
     { "_id" : 2},
     { $set : { "type" : "fiction",
                "rating" : "C"}}
)

See the execution of the code in the MongoDB shell:

After Update the documents

Here, see we successfully updated the document field using the updateOne() method.

Note that, the $set operation is used to replace the value of a field with the specified value and If the given field does not exist in the document, the $set operator will add the field to the specified value.

Read: Pros and cons of MongoDB

MongoDB update query with python

In MongoDB using python, you can update the content of existing documents using the update_one() method. This method is available in the pymongo library which is used to update a single document.

The method accepts a query like which document you want to update and update operation.

Example:

In this example, we will learn both the methods update_one() and update_many() and update the location value of a document in a collection by using python.

In python, the update_one() method is provided by the pymongo library that is used to update a single document that satisfies the defined condition.

Here, The below code is used to update a single document:

from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['myDB']

#Creating a collection
coll = db['example']

#Inserting document into a collection
data = [
   {"_id": "101", "name": "James", "age": "26", "city": "USA"},
   {"_id": "102", "name": "Michael", "age": "27", "city": "Australia"},
   {"_id": "103", "name": "Robert", "age": "28", "city": "Canada"}
]
res = coll.insert_many(data)
print("Data inserted")

#Retrieving all the records using the find() method
print("Documents in the collection: ")
for doc1 in coll.find():
   print(doc1)
coll.update_one({"_id":"103"},{"$set":{"city":"United States"}})

#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")

for doc2 in coll.find():
   print(doc2)

Output:

After executing the code you will get the output as given below:

MongoDB update query using python
MongoDB update query using python

Similarly, the update_many() method is also provided by the pymongo library and used to update multiple documents that satisfy the defined condition.

Here, The below code is used to update multiple documents:

import pymongo

#Creating a pymongo client
client = pymongo.MongoClient('localhost', 27017)
#Getting the database instance
db = client['myDB']
#Creating a collection
coll = db['example1']

#Inserting document into a collection
data = [
   {"_id": "101", "name": "James", "age": "26", "city": "Canada"},
   {"_id": "102", "name": "Michael", "age": "27", "city": "Australia"},
   {"_id": "103", "name": "Robert", "age": "28", "city": "New Zealand"}
]
res = coll.insert_many(data)
print("Data inserted")

#Retrieving all the records using the find() method
print("Documents in the collection: ")
for doc1 in coll.find():
    print(doc1)
coll.update_many({},{"$set":{"city":"United States of America"}})

#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")
for doc2 in coll.find():
   print(doc2)

Output:

After executing the code you will get the output as given below:

MongoDB updateMany documents using python
MongoDB updateMany documents using python

See both the outputs and we successfully updated the documents of a specific collection using python.

Read: How does MongoDB create a collection

MongoDB update document by id (ObjectId)

In MongoDB, Sometimes we only have to update the documents of a particular ID. For that, you have to define the particular ID in the update() method and after this, you can easily update the fields of the document. Let’s more understand with the help of an example.

Example:

In this example, we will learn to update the documents of a particular ID.

The following documents are inserted into the book collection.

> db.book.insertMany([
  {
    "_id" : 1,
    "item" : "MongoDB in Action",
    "stock" : 0,
    "info" : { "publisher" : "1111", "pages" : 480 },
    "tags" : [ "technology", "computer" ],
    "ratings" : [ { "by" : "Kyle", "rating" : 4 }, { "by" : "peter", "rating" : 5 } ],
    "reorder" : false
   },
   {
    "_id" : 2,
    "item" : "MongoDB: The Definitive Guide",
    "stock" : 15,
    "info" : { "publisher" : "5555", "pages" : 150 },
    "tags" : [ ],
    "ratings" : [ { "by" : "xyz", "rating" : 5 } ],
    "reorder" : false
   }
])

Check the documents of the book collection by using MongoDB Shell:

MongoDB update document by id
Insert documents into a collection

After inserting the documents into the book collection. Now we apply the update() method and update the document of a particular id.

> db.book.update(
    { _id: 1 },
    {
       $inc: { stock: 4 },
       $set: {
          item: "Data Modeling for MongoDB",
          "info.publisher": "2222",
          tags: [ "software" ],
          "ratings.1": {by: "Honey", rating: 3 }
}
    }
)

Here, we update the field of _id: 1. We use $inc to increment the stock by 4 and use the $set field to update the fields item, info. publisher, tags and ratings. You can also update more fields as per the question requirement.

Now see the execution of the code in the MongoDB shell:

MongoDB update document by id example
MongoDB update document by id

We successfully updated the documents of the book collection. The find() method is used to retrieve the document.

Read: MongoDB backup and restore

MongoDB update document with new field

In MongoDB, we can update the documents with a new field. It is the same as updating the existing collection field.

For this, we use the $set that is used to add new fields if the specified field does not exist.

You will more understand with the help of an example so let’s get started:

Example:

In this example, we add a new field in the existing collection field. The update() method inserts the new field if the specified field doesn’t exist.

The following documents are inserted into the students’ collection:

> db.students.insertMany([
    {
    "StudentName" : "John",
    "StudentAddress" : "US"
    },
    {
    "StudentName" : "David",
    "StudentAddress" : "UK"
    }
])

Check the documents by using MongoDB Shell:

MongoDB update document with new field
Insert documents into a collection

Now we apply the below update method to a new field if not exist:

> db.students.update(
    {},
    { $set: { "new_field": 1} },
)

Here, the $set will add a new field if the specified field does not exist.

Now see the execution of the code in the MongoDB shell:

MongoDB update document with new field example
MongoDB update document with a new field

See we successfully inserted a new field in the documents.

Note that, In case you want to add a new_field to all your collection then you have to use an empty selector, and set the multi flag to true to update all the documents.

db.your_collection.update({},
                          {$set : {"new_field":1}},
                          {upsert:true,
                          multi:false}) 

Upsert: If you set upsert as true then it creates a new document when no document matches the query criteria.

Multi: If you set multi as true then it updates multiple documents that meet the query criteria. If set to false, update one document.

Read: How to create a new database in MongoDB

MongoDB update document where

In MongoDB, we update the documents with the help of updateOne() or updateMany() method. Here, where use is to match documents that satisfy the expression, and after that, we update the documents of the collection by using the update method.

You will more understand with the help of an example so let’s get started.

Example:

In this example, we will update a particular field according to the where condition.

The following documents are inserted into the details collection:

> db.details.insertMany(
	[
		{
			First_Name: "James",
			Last_Name: "Shaw",
			Age: "25",
			e_mail: "James_Shaw.123@gmail.com",
			phone: "9000012345"
		},
		{
			First_Name: "Rachel",
			Last_Name: "John",
			Age: "28",
			e_mail: "Rachel_John.123@gmail.com",
			phone: "9000054321"
		},
		{
			First_Name: "George",
			Last_Name: "Wood",
			Age: "23",
			e_mail: "George_Wood.123@gmail.com",
			phone: "9000054321"
		}
	]
)

Check the documents by using MongoDB Shell:

MongoDB update document where
Insert documents into the collection

After inserting the documents, Now we apply the where condition and update the documents of a particular field.

db.details.updateOne(
    { First_Name: "James"},
    { $set: { Age: "29", e_mail: "James_Shaw.321@gmail.com"}}
)

Here, the update method is used to update the documents where First_name is James. And we update the Age and e_mail field with the help of the $set(aggregation).

Note that, the $set operator replaces the value of a field with the specified value.

Now see the execution of the code in the MongoDB shell:

MongoDB update document where example
MongoDB update document where

We successfully updated the documents of the details collection. The find() method is used to retrieve the document.

MongoDB related tutorials:

In this tutorial, you have learned How to update documents into MongoDB with different operations and examples. These are the following topics that we covered 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