How to update mongodb document in a collection ?

The tutorial provides the steps to update the document in MongoDB. A record or document is updated in mogodb using update() , updateOne(), updateMany(), replaceOne() which we will discuss in details with examples

Update Document in MongoDB

The below needs to be considered when updating a document in MongoDB

  • MongoDB allows to update a single document in the collection
  • MongoDB allows to update multiple documents in the collection
  • MongoDB allows to replace a single document in the collection
S. No MongoDB Update Methods Update Method Description
1 db.collection.update() The method updates a single document or multiple document which matches the given update criteria
2 db.collection.updateOne() The method updates a single document which matches the given update criteria
3 db.collection.updateMany() The method updates multiple document or multiple document which matches the given update criteria
4 db.collection.replaceOne() The method replaces a single document which matches the given update criteria
5 db.collection.findOneAndReplace() The method replaces a single document which matches the given update criteria
6 db.collection.findOneAndUpdate() The method updates a single document which matches the given update and sorting criteria
7 db.collection.findAndModify() The method modifies and return the single document. This method is useful when need to return the document with the modifications on the update. By default return document does not provide any details on modification being done.
8 db.collection.save() This method allows to insert new document or update the existing document.
9 db.collection.bulkWrite() This method includes Array parameter to allow multiple write operation with the order of execution.

Method Name: update()

Syntax: db.collection.update(<Update_Criteria>,<update>)

The db.collection.update() methods allows to update a single document or multiple documents in a collection.

Example: Retrieve the existing record from the collection – oracleappsUsers

> db.oracelappsUsers.findOne({name: "Mohit Sharma"})
{
"_id" : ObjectId("5f12fd48d4a587e31cddd7e5"),
"name" : "Mohit Sharma",
"userType" : "Admin",
"description" : "MongoDB insert document sample",
"createdBy" : "oracelappshelp.com"
}

Now update the userType from “Admin” to “Administrator”

> db.oracelappsUsers.update({'userType':'Admin'},{$set:{'userType':'Administrator'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Now Retrieve the same record and userType should be updated to ‘Administrator’

db.oracelappsUsers.findOne({name: "Mohit Sharma"})
{
"_id" : ObjectId("5f12fd48d4a587e31cddd7e5"),
"name" : "Mohit Sharma",
"userType" : "Administrator",
"description" : "MongoDB insert document sample",
"createdBy" : "oracelappshelp.com"
}

Method Name: updateOne()

Syntax: db.collection.updateOne(<Update_Criteria>,<update>, <options>)

The updateOne() allows MongoDB to update a single document in a collection.

Example: Create a new record in collection – oracleappsUsers

> db.oracelappsUsers.insert({
… name: "Amit Srivastava",
… userType: "subscriber",
… description: "MongoDB insert document sample",
… createdBy: "oracelappshelp.com"
… })
WriteResult({ "nInserted" : 1 })

Now Retrieve the inserted document using findOne( )

> db.oracelappsUsers.findOne({name: "Amit Srivastava"})
{
"_id" : ObjectId("5f13c9df9104ecc5b2149d60"),
"name" : "Amit Srivastava",
"userType" : "subscriber",
"description" : "MongoDB insert document sample",
"createdBy" : "oracelappshelp.com"
}

Now , update the record name from ‘Amit Srivastava’  to ‘Amit Trivedi’ using updateOne()

> db.oracelappsUsers.updateOne(
… {name: 'Amit Srivastava'},
… { $set: { name: 'Amit Trivedi'}}
… )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Retrieve the updated document result

db.oracelappsUsers.findOne({name: "Amit Trivedi"})
{
"_id" : ObjectId("5f13c9df9104ecc5b2149d60"),
"name" : "Amit Trivedi",
"userType" : "subscriber",
"description" : "MongoDB insert document sample",
"createdBy" : "oracelappshelp.com"
}

Method Name: updateMany()

Syntax: db.collection.updateMany(<Update_Criteria>,<update>, <options>)

The method updateMany() allows MongoDB to update multiple documents in a collection.

Example: Retrieve the list of document in a collection using find()

> db.oracelappsUsers.find().pretty()
{
"_id" : ObjectId("5f13c9df9104ecc5b2149d60"),
"name" : "Amit Trivedi",
"userType" : "subscriber",
"description" : "MongoDB insert document sample",
"createdBy" : "oracelappshelp.com"
}
{
"_id" : ObjectId("5f13ce54a3587b86324785d9"),
"name" : "Rohit Verma",
"userType" : "subscriber",
"description" : "MongoDB insert document Tutorial",
"createdBy" : "oracelappshelp.com"
}
{
"_id" : ObjectId("5f13ce7ca3587b86324785da"),
"name" : "Mohit Sharma",
"userType" : "subscriber",
"description" : "MongoDB insert document sample",
"createdBy" : "oracelappshelp.com"
}

Now Update the userType from ‘Subscriber’ to ‘Admin’ using updateMany()

> db.oracelappsUsers.updateMany(
… {userType: 'subscriber'},
… { $set: { userType: 'Admin'}}
… )
{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }

Retrieve the updated documents from the collection

> db.oracelappsUsers.find().pretty()
{
"_id" : ObjectId("5f13c9df9104ecc5b2149d60"),
"name" : "Amit Trivedi",
"userType" : "Admin",
"description" : "MongoDB insert document sample",
"createdBy" : "oracelappshelp.com"
}
{
"_id" : ObjectId("5f13ce54a3587b86324785d9"),
"name" : "Rohit Verma",
"userType" : "Admin",
"description" : "MongoDB insert document Tutorial",
"createdBy" : "oracelappshelp.com"
}
{
"_id" : ObjectId("5f13ce7ca3587b86324785da"),
"name" : "Mohit Sharma",
"userType" : "Admin",
"description" : "MongoDB insert document sample",
"createdBy" : "oracelappshelp.com"
}

Method Name: findOneAndReplace()

Syntax:

db.collection.findOneAndReplace(
   <filter>,
   <replacement>,
   {
     projection: <document>,
     sort: <document>,
     maxTimeMS: <number>,
     upsert: <boolean>,
     returnNewDocument: <boolean>,
     collation: <document>
   }
)
Parameter Parameter Type Parameter Description
filter Document depicts the update criteria
replacement Document depicts the document to be replaced but cannot contain Update Operators
projection Document depicts the sub set of fields to return
sort Document specifies the sorting order matched as per the filter.
maxTimeMS Number specifies the time for the operation to complete
upsert Boolean

Default value is False. Replaces the document with the matched filter and returns returnNewDocument  as true .

If does not match replacement, then insert as new document and returns Null.

returnNewDocument Boolean returns the replacement document instead of the original document
collation Document allows to specify language-specific rules for string comparison

Method Name – save()

This method allows to insert new document or update the existing document. This method is deprecated in MongoDB.

Syntax

> db.collection.save(
  <document>,
  {
    writeConcern:<document>
  }
)

Example:

> db.orders.save( { item: "Laptop", qty: 10 , price:4000, status:"Processed" } )

Update Operators in MongoDB

The below given are the update operators in MongoDB.

S. No  Operator Name Operator Description
1 $currentDate set the value of a field to current date as or TimeStamp
2 $inc increments the value
3 $min updates the document when provided value is less than the existing field value
4 $max updates the document when provided value is greater than the existing field value
5 $mul allows to multiply the field value
6 $rename renames the field in a document
7 $set set the value of a field in a document
8 $setOnInsert set the value of a field for the new document
9 $unset removes the value of a field in a document