Friday 4 June 2021

MongoDB: replaceOne: Replace one document

‘replaceOne’ method replace single document that matches to given filter criteria.

 

Signature

db.collection.replaceOne(
   <filter>,
   <replacement>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     hint: <document|string>                   // Available starting in 4.2.1
   }
)

 

Example

db.employee.replaceOne({"lastName" : "nzv"}, {"deleted" : true, "deletedTime" : Date.now()})

 

Let’s experiment with employee collection.

> db.employee.find().pretty()
{
      "_id" : ObjectId("60bb035bbaf44d88348459c5"),
      "firstName" : "Sailja",
      "lastName" : "PTR",
      "active" : true,
      "modifiedTime" : 1622868890184
}
{
      "_id" : ObjectId("60bb062abaf44d88348459c7"),
      "firstName" : "Rohini",
      "lastName" : "Shankar"
}
{
      "_id" : ObjectId("60bb06e6baf44d88348459c8"),
      "firstName" : "Trinadh",
      "lastName" : "nzv"
}
{
      "_id" : ObjectId("60bb07d3baf44d88348459c9"),
      "firstName" : "Shankar",
      "lastName" : "nzv"
}

Replace one document whose lastName is nzv.

> db.employee.replaceOne({"lastName" : "nzv"}, {"deleted" : true, "deletedTime" : Date.now()})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> 
> db.employee.find().pretty()
{
      "_id" : ObjectId("60bb035bbaf44d88348459c5"),
      "firstName" : "Sailja",
      "lastName" : "PTR",
      "active" : true,
      "modifiedTime" : 1622868890184
}
{
      "_id" : ObjectId("60bb062abaf44d88348459c7"),
      "firstName" : "Rohini",
      "lastName" : "Shankar"
}
{
      "_id" : ObjectId("60bb06e6baf44d88348459c8"),
      "deleted" : true,
      "deletedTime" : 1622870057702
}
{
      "_id" : ObjectId("60bb07d3baf44d88348459c9"),
      "firstName" : "Shankar",
      "lastName" : "nzv"
}




 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment