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.

The Ultimate Ticket to Top Data Science Job Roles

Post Graduate Program In Data ScienceExplore Now
The Ultimate Ticket to Top Data Science Job Roles

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.

Get In-Demand Skills to Launch Your Data Career

Big Data Hadoop Certification Training CourseExplore Course
Get In-Demand Skills to Launch Your Data Career

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.

Choose the Right Program

Accelerate your career with Simplilearn's Data Science courses! Choose the right program tailored to your needs and become a data wizard. Gain in-demand skills, learn from industry experts, and unlock exciting job opportunities. Don't miss out on this chance to become a sought-after data scientist. Enroll today!

Program Name

DS Master's

Post Graduate Program In Data Science

Professional Certificate Course In Data Science

Geo All Geos IN/ROW IN
University Simplilearn Caltech IIT Kanpur
Course Duration 11 Months 11 Months 11 Months
Coding Experience Required Basic No Yes
Skills You Will Learn 10+ skills including data structure, data manipulation, NumPy, Scikit-Learn, Tableau and more 8+ skills including
Supervised & Unsupervised Learning
Deep Learning
Data Visualization, and more
8+ skills including
NLP, Data Visualization, Model Building, and more
Additional Benefits Applied Learning via Capstone and 25+ Data Science Projects Upto 14 CEU Credits Caltech CTME Circle Membership Live masterclasses from IIT Kanpur faculty and certificate from E&ICT Academy, IIT Kanpur
Cost $$ $$$$ $$$
Explore Program Explore Program Explore Program

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 PG in Data Science 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. 

Our Big Data Courses Duration And Fees

Big Data Courses typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Post Graduate Program in Data Engineering

Cohort Starts: 25 Apr, 2024

8 Months$ 3,850