Skip to content

Spoke Right

Education for everyone

https://spokeright.com
Primary Menu
  • Home
  • Our Services
    • Translation
    • Interpretation
    • Transcription
    • Voice-Over
    • Proofreading
    • Content writing
  • Free Education
    • Learn Android Studio
    • Learn Python
    • Learn MongoDB
    • Learn MySql
    • Learn React
    • Montessori Education
  • Spoke Right News
  • Earn Online
  • Classic Games by Spoke Right
    • TicTac
    • Checkers
    • Foosball
    • Billiards
    • Master Chess
    • Logic Game
  • Contact Us
Download Now
  • Home
  • Learn MongoDB
  • How to Update a Document
  • Learn MongoDB

How to Update a Document

Spoke Right December 21, 2022 4 min read

Update A Document

MongoDB’s update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method.

MongoDB Update() Method

The update() method updates the values in the existing document.

Syntax

The basic syntax of update() method is as follows −

>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)

Example

Consider the mycol collection has the following data.

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}

Following example will set the new title ‘New MongoDB Tutorial’ of the documents whose title is ‘MongoDB Overview’.

>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
>

By default, MongoDB will update only a single document. To update multiple documents, you need to set a parameter ‘multi’ to true.

>db.mycol.update({'title':'MongoDB Overview'},
   {$set:{'title':'New MongoDB Tutorial'}},{multi:true})

MongoDB Save() Method

The save() method replaces the existing document with the new document passed in the save() method.

Syntax

The basic syntax of MongoDB save() method is shown below −

>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

Example

Following example will replace the document with the _id ‘5983548781331adf45ec5’.

>db.mycol.save(
   {
      "_id" : ObjectId("507f191e810c19729de860ea"), 
		"title":"Tutorials Point New Topic",
      "by":"Tutorials Point"
   }
)
WriteResult({
	"nMatched" : 0,
	"nUpserted" : 1,
	"nModified" : 0,
	"_id" : ObjectId("507f191e810c19729de860ea")
})
>db.mycol.find()
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point New Topic",
   "by":"Tutorials Point"}
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"NoSQL Overview"}
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point Overview"}
>

MongoDB findOneAndUpdate() method

The findOneAndUpdate() method updates the values in the existing document.

Syntax

The basic syntax of findOneAndUpdate() method is as follows −

>db.COLLECTION_NAME.findOneAndUpdate(SELECTIOIN_CRITERIA, UPDATED_DATA)

Example

Assume we have created a collection named empDetails and inserted three documents in it as shown below −

> db.empDetails.insertMany(
	[
		{
			First_Name: "Radhika",
			Last_Name: "Sharma",
			Age: "26",
			e_mail: "[email protected]",
			phone: "9000012345"
		},
		{
			First_Name: "Rachel",
			Last_Name: "Christopher",
			Age: "27",
			e_mail: "[email protected]",
			phone: "9000054321"
		},
		{
			First_Name: "Fathima",
			Last_Name: "Sheik",
			Age: "24",
			e_mail: "[email protected]",
			phone: "9000054321"
		}
	]
)

Following example updates the age and email values of the document with name ‘Radhika’.

> db.empDetails.findOneAndUpdate(
	{First_Name: 'Radhika'},
	{ $set: { Age: '30',e_mail: '[email protected]'}}
)
{
	"_id" : ObjectId("5dd6636870fb13eec3963bf5"),
	"First_Name" : "Radhika",
	"Last_Name" : "Sharma",
	"Age" : "30",
	"e_mail" : "[email protected]",
	"phone" : "9000012345"
}

MongoDB updateOne() method

This methods updates a single document which matches the given filter.

Syntax

The basic syntax of updateOne() method is as follows −

>db.COLLECTION_NAME.updateOne(<filter>, <update>)

Example

> db.empDetails.updateOne(
	{First_Name: 'Radhika'},
	{ $set: { Age: '30',e_mail: '[email protected]'}}
)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }
>

MongoDB updateMany() method

The updateMany() method updates all the documents that matches the given filter.

Syntax

The basic syntax of updateMany() method is as follows −

>db.COLLECTION_NAME.update(<filter>, <update>)

Example

> db.empDetails.updateMany(
	{Age:{ $gt: "25" }},
	{ $set: { Age: '00'}}
)
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }

You can see the updated values if you retrieve the contents of the document using the find method as shown below −

> db.empDetails.find()
{ "_id" : ObjectId("5dd6636870fb13eec3963bf5"), "First_Name" : "Radhika", "Last_Name" : "Sharma", "Age" : "00", "e_mail" : "[email protected]", "phone" : "9000012345" }
{ "_id" : ObjectId("5dd6636870fb13eec3963bf6"), "First_Name" : "Rachel", "Last_Name" : "Christopher", "Age" : "00", "e_mail" : "[email protected]", "phone" : "9000054321" }
{ "_id" : ObjectId("5dd6636870fb13eec3963bf7"), "First_Name" : "Fathima", "Last_Name" : "Sheik", "Age" : "24", "e_mail" : "[email protected]", "phone" : "9000054321" }
>

Update a Single Document

The following example uses the db.collection.updateOne() method on the inventory collection to update the first document where item equals "paper":

db.inventory.updateOne(
{ item: “paper” },
{
$set: { “size.uom”: “cm”, status: “P” },
$currentDate: { lastModified: true }
}
)
MongoDB Shell

The update operation:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of the status field to "P",

  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.

db.inventory.updateMany(
{ “qty”: { $lt: 50 } },
{
$set: { “size.uom”: “in”, status: “P” },
$currentDate: { lastModified: true }
}
)
MongoDB Shell

The update operation:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of the status field to "P",

  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.

db.inventory.replaceOne(
{ item: “paper” },
{ item: “paper”, instock: [ { warehouse: “A”, qty: 60 }, { warehouse: “B”, qty: 40 } ] }
)

Continue Reading

Previous: How to Query a Document
Next: How to delete a documents

Related Stories

How to use Auto-Increment Sequence MongoDB
2 min read
  • Learn MongoDB

How to use Auto-Increment Sequence MongoDB

December 28, 2022
What is capped collection MongoDB
2 min read
  • Learn MongoDB

What is capped collection MongoDB

December 28, 2022
What is GridFS in MongoDB
2 min read
  • Learn MongoDB

What is GridFS in MongoDB

December 28, 2022

This AD Will support Us

Support Us

Coding Ustad LTD Support
Coding Ustad LTD Support

Coding Ustad LTD

Coding Ustad LTD
Coding Ustad LTD

Recent Posts

  • How to Install Node.js and npm on CentOS 7
  • How to Install Node.js and npm on CentOS 7
  • How to Install CentOS Web Panel (CWP) on CentOS 7
  • The Power of Marketing in Real Estate: A Guide to Boost Your Business
  • Vehicle Verification in Pakistan

Get free Hosting

Hostens.com - A home for your website

You may have missed

How to Install Node.js and npm on CentOS 7
4 min read
  • Coding Ustad LTD
  • Education for Everyone

How to Install Node.js and npm on CentOS 7

May 3, 2023
How to Install Node.js and npm on CentOS 7
4 min read
  • Coding Ustad LTD
  • Education for Everyone

How to Install Node.js and npm on CentOS 7

May 2, 2023
How to Install CentOS Web Panel (CWP) on CentOS 7
3 min read
  • Coding Ustad LTD
  • Education for Everyone

How to Install CentOS Web Panel (CWP) on CentOS 7

May 2, 2023
The Power of Marketing in Real Estate: A Guide to Boost Your Business https://thaikadar.com/secureinvestment/
2 min read
  • Article By Spoke Right
  • Blog By Spoke Right
  • Circular Byte Private Limited

The Power of Marketing in Real Estate: A Guide to Boost Your Business

January 30, 2023
  • Home
  • Our Services
  • Free Education
  • Spoke Right News
  • Earn Online
  • Classic Games by Spoke Right
  • Contact Us
Copyright © All rights reserved. | MoreNews by AF themes.