Table of contents
1.
Introduction
1.1.
Document
1.2.
Collection
2.
MongoDB Update Document
2.1.
update() Method
2.2.
UpdateOne() Method
2.3.
UpdateMany() Method
2.4.
findOneAndReplace() Method
3.
Frequently Asked Questions
4.
Key Takeaways
Last Updated: Mar 27, 2024

MongoDB Update document

Author Sneha Mallik
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The data in MongoDB has a flexible schema. We do not need to declare the new columns of a collection in MongoDB before entering data into the database, as we would in a traditional RDBMS(Relational Database Management System). So, when developing a schema in MongoDB, there are a few basic things to keep in mind.

  • We need to create a schema that meets our needs.
  • If we use two items together, we must merge them into a single object.
  • Joins can be performed while the data is being written.
  • Our schema has to be optimized for the most common data searches.
  • We can handle the most complicated data aggregation tasks.

Document

In MongoDB, a document is the fundamental data unit, which is relatively similar to a row in relational databases.

A document is a collection of keys with data or values associated with them. Every programming language has its own representation of these documents, although the basic structure of these documents is usually a map, hash, or dictionary. A document is an object in JavaScript, just like in the example below.

 

Document in the collection

{"message" : "Hello, MongoDB"}

 

The key "message" in the above document sample has the value "Hello, MongoDB." Most documents have a more comprehensive structure that includes several nested key-value pairs. A document's key is often made up of string data. Instead, there are always some notable exceptions in the key.

There are no null characters in the key. If a null character appears in a key, it implies the key has come to an end.

Some special characters (such as $ or .) are reserved for specific situations. These are reserved characters.

Collection

According to the RDBMS concept, a collection in MongoDB can be regarded as a Table. The collection is essentially a gathering of documents. Dynamic schemas are always present in MongoDB collections. This means that documents in a single collection might have various elements and shapes. 

For example:

[
{
  "_id" : ObjectId("61a8f4b791f30e5db6642602"),
  "name" : "Sapna",
  "phoneNumber" : "0123456789"
},
{
  "_id" : ObjectId("61a8f59d91f30e5db6642603"),
  "name" : "Simran",   
  "phoneNumber" : "123321123"
},
{
  "_id" : ObjectId("61a8f5dd91f30e5db6642604"),
  "name" : "Aman",
  "phoneNumber" : "456654456"
}
]

 

Refer here to learn more about creating MongoDB databases, collections, and documents. 

MongoDB Update Document

The database can be updated using one of four MongoDB Update methods. Within MongoDB, each method has a specific reason for being performed.

The following are the update methods:

  • Update()
  • UpdateOne()
  • UpdateMany()
  • ReplaceOne()

To update a document from the MongoDB collection, use any methods listed above. 

update() Method

The update method is used to make changes to a document that already exists in the collection.

Depending on the criteria of an update, you can change a specific field for the entire document. The update technique is used to edit only one record by default. If you want to update many documents, use the "multi: true" option in the update method's options parameter.

Syntax for mongoDB Update:

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

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

query: The query parameter is the update method's selection criterion. The name is the selection criteria if you wish to update a student's age in the collection who has a specific name.

 

update: You can use this argument to specify what you wish to change in an existing record. Assume the document includes three fields: name, age, and class.

The student's class must then be updated by name. You'll pass $set with the field you want to edit in the update parameter. Mongo push is required to update an array.

 

options: As an update method, we have a variety of options to choose from. But we'll concentrate on both of them because they're necessary to know.

The first option is "upset," which, if true, means that if it tries to alter a non-existing document, it will generate a new record. If the value is false, it will not attempt to update a non-existing document by inserting a new record.

If the default value is false, the second option, "multi," is used to apply criteria to multiple documents within a collection. If the value is true, the changes will be applied to all documents that satisfy the query criteria entirely.

For example: 

Let us update the student’s phone number by having the name “Aman”.

db.students.update({name: "Aman"}, {$set:{phoneNumber: ”456654676”}})

 

The first parameter is the name of the student whose phone number is to be modified {name: "Aman"}, and the second parameter is the set keyword, which means to set(update) the next matched key value with the older key value, i.e., from 456654456 to 456654676.

 

Output

The ‘Output' shows the updated collection after running the query, and we can see that the phone number has been updated from 456654456 to 456654676.

UpdateOne() Method

db.collection_name.updateOne() locates the first document that meets the filter and updates it with the provided changes.

Syntax:

db.collection_name.updateOne(
{Selection_Criteria}, {$set:{Update_data}}, 
{
    upsert: <boolean>,
    writeConcern: <document>,
    collation: <document>,
    arrayFilters: [<filterdocument1>, ... ],
    hint: <document|string>        
})

 

Parameters:

Parameter

Description

upsert

This parameter's default value is false. If true, it will create a new document in the collection if no document meets the update method's criterion.

writeConcern

This parameter is used when you don't want to utilize the default write concern. This parameter has the type of document.

collation

It describes how the collation will be used in operations. Users can set language-specific string comparison criteria, such as rules for letter case and accent marks. This parameter has the type of document.

arrayFilters

It's an array of filter documents that tell an array field update which array elements to change. This parameter has an array as its type.

hint

It's a document or field that provides 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.

 

 

 

Return:

Field

Description

nMatched

This field contains the total number of documents that have been matched.

modifiedCount

This field contains the total number of documents that have been modified or updated.

upsertedId

The upserted document's _id is stored in this field.

acknowledged

If write concern was enabled, the value of this field is true; otherwise, it is false.

 

For example:-

Let us update the phone number of the student having the name “Sapna”.

db.students.updateOne({name: "Sapna"}, {$set:{phoneNumber: 456654456}})

 

The first parameter is the name of the student whose phone number is to be modified {name: "Sapna"}, and the second parameter is the set keyword, which means to set(update) the next matched key value with the older key value, i.e., from 0123456789 to 456654456.

 

Output

The ‘Output' shows the updated collection after running the query and we can see that the phone number has been updated from 0123456789 to 456654456.

UpdateMany() Method

updateMany() applies modifications to all matching documents in the collection that matches the filter, using the update criteria.

Syntax:

db.collection_name.updateMany(
<filter>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>
}
)

 

Parameters:

Parameter

Description

upsert

This parameter's default value is false. If true, it will create a new document in the collection if no document meets the update method's criterion.

multi

This parameter's default value is false. The update method changes all documents that meet the query criteria when it is true. Otherwise, only one document will be updated.

writeConcern

This parameter is used when you don't want to utilize the default write concern. This parameter has the type of document.

collation

It describes how the collation will be used in operations. Users can set language-specific string comparison criteria, such as rules for letter case and accent marks. This parameter has the type of document.

arrayFilters

It's an array of filter documents that tell an array field update which array elements to change. This parameter has an array as its type.

hint

It's a document or field that provides 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.

 

Return:

Field

Description

matchedCount

This field contains the total number of documents that have been matched.

modifiedCount

This field contains the total number of documents that have been modified or updated.

upsertedId

The upserted document's _id is stored in this field.

acknowledged

If write concern was enabled, the value of this field is true; otherwise, it is false.

 

For example:-

Let us update the phone number of the student having the name “Simran”.

db.student.updateMany({name: "Simran"}, {$set:{phoneNumber: 123321124}})

 

Using the updateMany() method, we update the 'phone number' of a student named 'Simran' from 123321123 to 123321124.

Output

The ‘Output' shows the updated collection after running the query, and we can see that the phone number has been updated from 123321123 to 123321124.

findOneAndReplace() Method

Based on the filter, it replaces the first single document matched in the collection.

Syntax:

db.collection_name.findOneAndReplace(
selection_criteria:<document>,
replacement: <document>,
{
    projection: <document>,
    sort: <document>,
    maxTimeMS: <number>,
    upsert: <boolean>,
    returnNewDocument: <boolean>,
    collation: <document>
  }) 

 

Parameters:

Parameter

Description

projection

This parameter's type is a document. It decides which fields are returned to the documents which matched.

sort

If the query selects multiple documents, it determines which document the operation will modify. The first document in the sort order indicated by this argument will be replaced by findOneAndReplace(). This parameter's type is a document.

maxTimeMS

This parameter's type is number. It defines a millisecond time limit within which the operation must be completed. If the time limit is exceeded, an error is thrown.

upsert

This parameter's default value is false. If true, it will create a new document in the collection if no document meets the update method's criterion.

returnNewDocument

This parameter's type is boolean. This function returns the original document by default. Set value of the returnNewDocument option to true to return the replacement document.

collation

It describes how the collation will be used in operations. Users can set language-specific string comparison criteria, such as rules for lettercase and accent marks. This parameter has the type of document.

 

 

 

 

Return:

This function returns the original document by default. Set value of the returnNewDocument option to true to return the replacement document.

 

For example:-

db.students.findOneAndReplace({phoneNumber : 123321124},{name:"Samir", phoneNumber : 123321123})

 

Output

The ‘Output' shows the updated collection after running the query, and we can see that the phone number 123321123 has been updated from 123321124 to 123321123.

Frequently Asked Questions

1. Explain what is meant by the MongoDB update.

Ans: 

MongoDB Update: The update() method in MongoDB is used to update or modify a collection's existing documents.

Syntax:

db.collection_name.update(selection_criteria, updated_data)

 

2. How do you update a specific key/value of an array field in MongoDB?

Ans: Let us consider a collection of content, which includes articles, news, and other items. These articles contain a separate array named author, which contains all of the author's information.

The first option is "upset," which is false; it will not attempt to update a non-existing document by inserting a new record.

If the default value is true, the changes will be applied to all documents that satisfy the query criteria entirely.

db.content.update({
'authors.abc':'xyz'
},
{$set:{'authors.$.address':'Address That I wanted'}},false,true
);

Key Takeaways

In this blog, we went over the concept of MongoDB update documentsThe update method is used to change specified fields throughout a MongoDB document collection. In this blog, we covered how to update single or several documents based on specific criteria in this article. 

Enroll in our Full Stack Web Development Course — MERN Stack to deeply understand the concept of MongoDB update documents in Web Development. 

Credits: GIPHY

Happy Developing!

Live masterclass