MongoDB is a pioneer in modern, general-purpose database platform that allows applications and the developers who create them to harness the power of software and data. MongoDB, based in New York, has over 33,000 customers in more than 100 countries. Over 240 million people have downloaded the MongoDB database platform, and more than 1.5 million people have signed up for MongoDB University courses.

In this article, we will be discussing how to Update a Document in MongoDB.

Post Graduate Program In Data Science

The Ultimate Ticket To Top Data Science Job RolesExplore Course
Post Graduate Program In Data Science

What is the MongoDB Update Document?

To update a document in MongoDB, we use the update() method.

The update() method refreshes the values in a MongoDB collection's existing document. The _id field's value does not change when you update your document. The db.collection.update() method, by default, only updates one document. Use the multi: true option to update all documents that match the query. 

This approach can be used to update a single document as well as multiple documents at the same time.

Syntax

db.COLLECTION_NAME.update({SELECTION_CRITERIA}, {$set:{UPDATED_DATA}}, {

     upsert: <boolean>,

     multi: <boolean>,

     writeConcern: <document>,

     collation: <document>,

     arrayFilters: [ <filterdocument1>, ... ],

     hint:  <document|string>        

   })

Now, let us discuss the parameters required for the update() method in MongoDB.

Parameters for MongoDB Update Document

Some of the Parameters required for the MongoDB update() method are given below.

Non-Negotiable Parameters

  • The Older value in Documents is the first parameter. Similar to JSON objects, documents are made up of file and value pairs.
  • To alter the next specified document value, the second parameter must have the $set keyword.
  • The third parameter can be left blank if you don't want to use it, i.e., it is optional.

Optional Parameters

  • Collation: This describes the collation used in operations. A user can easily set language-specific string comparison criteria, like rules for letter case and accent marks.
  • Upsert: Upset parameter's default value is false. If it changes to true, it will create a new document in the collection if no other document meets the update method's criterion.
  • hint: It's a file or field that specifies the index that will be used to support the filter. It can accept an index specification document or an index name string, and it will return an error if you specify an index that does not exist.
  • multi: This parameter's default value is false. When this parameter is set to true, the update method updates all documents that satisfy the query condition. Otherwise, only one document will be updated.
  • arrayFilters: This is an array of filter documents that tell the update operation on an array field which array items to modify. This parameter has the type of array.
  • writeConcern: Only use writeConcern if you don't want to utilize the default write concern. This option has the type of document.

Let us now discuss how to update a Single Document using MongoDB.

How to Update a Single Document?

To update a single document in MongoDB, the following steps are followed:

  • First, utilize the update() method.

Syntax

db.collection.update(query, update, options) 

  • Specify the condition that will be applied to the document when it is updated. We need to edit the document with the Employee id of 100 in the example below.
  • To update the values, use the $set operator.
  • Select the Field Name that has to be modified and fill in the new values –

Employee_Name = ”Keerthana Suresh”

db.Employees.update(

{"Emp_ID" :100},

{$set:{"Employee_Name" :"Keerthana Suresh"}});

WriteResult({"nMatched": 1,  "nUpserted: 0, "nModified":1 })

MongoDB_Update_Doc_1

Now that we have understood how to update a single document in MongoDB, let us see how to Update Multiple Documents using MongoDB.

MongoDB Developer and Administrator: Free Course

MongoDB Developer & Administrator Basics for FREEStart Learning
MongoDB Developer and Administrator: Free Course

How to Update Multiple Documents?

In MongoDB, we must use the multi option to update several documents at once. Otherwise, only one document will be updated at a time by default.

The example below demonstrates how to update a large number of documents. In this example, we'll find the document with the Emp ID id of 10, modify the Emp ID to 32, and alter the Employee Name to "Stacy Fowler". 

Follow the steps below to update multiple documents:

  • First, use the MongoDB update() method.

Syntax

db.collection.update(query, update, options) 

  • Indicate the condition that will be used to update the document. We need to edit the document with the Employee id of 10 in the example below.
  • To update the values, use the $set operator.
  • Select the Names of the Fields that need to be modified and fill in the new values –

Employee_Name =”Stacy Fowler”

Emp_ID = 32

db.Employees.update({ Emp_ID : 10},{$set :{"Employee_Name" : "Stacy Fowler"," Emp_ID" : 32}})

MongoDB_Update_Doc_2

What if the Update Operation Doesn’t Match Documents in the Collection? 

If the update operation does not match any documents in the collection, the upsert option can be set to true to immediately insert a document that is new into the collection that meets the update query.

db.Employees.update(

{type:"PartTime"},

{$set:{salary:1500000}},

{upsert : true}

)

WriteResult ("nMatched": 0; "nUpserted": 1; "nModified":1)

MongoDB_Update_Doc_3

The upsert is also represented in the Write Result of the preceding procedure.

MongoDB's upsert operation is utilized to save documents into collections.

If the document meets the query conditions, it will be updated; else, it will be added to the collection as a new document.

Simplilearn's PG Program in Data Science in partnership with Purdue University and in collaboration with IBM, is ranked #1 Post Graduate in Data Science program by ET. If you wish to ace data science, this program is just the one for you!

Become an Expert in Data Science With Simplilearn

In this article, we discussed how to update documents in MongoDB using the update() method of MongoDB and its various attributes. To dive deep into data manipulation techniques and become a better data scientist, one must explore more resources that are standardized and scheduled.

One such data science course is offered by Simplilearn to make you a better data scientist. Learn data science in collaboration with Purdue University and IBM and kickstart your data science journey in just 12 months. 

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.