Friday 4 June 2021

MongoDB: updateOne: Update one document

Update one document that satisfies the filter criteria.

 

Syntax

db.collection.updateOne(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        // Available starting in MongoDB 4.2.1
   }
)

Example

db.employee.updateOne({"active" : true}, {$set : {"active" : false, "modifiedTime" : Date.now()}})

Above snippet update one matching document.

 

Actual Data

> db.employee.find().pretty()
{
      "_id" : ObjectId("60baff65baf44d88348459bf"),
      "firstName" : "Krishna",
      "lastName" : "Gurram",
      "active" : true
}
{
      "_id" : ObjectId("60baff6dbaf44d88348459c0"),
      "firstName" : "Ram",
      "lastName" : "Gurram",
      "active" : true
}
{
      "_id" : ObjectId("60baff75baf44d88348459c1"),
      "firstName" : "Thulasi",
      "lastName" : "Gurram",
      "active" : true
}
{
      "_id" : ObjectId("60baff83baf44d88348459c2"),
      "firstName" : "Gopi",
      "lastName" : "Battu",
      "active" : true
}
{
      "_id" : ObjectId("60baff8fbaf44d88348459c3"),
      "firstName" : "Sailaja",
      "lastName" : "PTR",
      "active" : true
}


After executing updateOne query

> db.employee.updateOne({"active" : true}, {$set : {"active" : false, "modifiedTime" : Date.now()}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> 
> 
> db.employee.find().pretty()
{
      "_id" : ObjectId("60baff65baf44d88348459bf"),
      "firstName" : "Krishna",
      "lastName" : "Gurram",
      "active" : false,
      "modifiedTime" : 1622868001073
}
{
      "_id" : ObjectId("60baff6dbaf44d88348459c0"),
      "firstName" : "Ram",
      "lastName" : "Gurram",
      "active" : true
}
{
      "_id" : ObjectId("60baff75baf44d88348459c1"),
      "firstName" : "Thulasi",
      "lastName" : "Gurram",
      "active" : true
}
{
      "_id" : ObjectId("60baff83baf44d88348459c2"),
      "firstName" : "Gopi",
      "lastName" : "Battu",
      "active" : true
}
{
      "_id" : ObjectId("60baff8fbaf44d88348459c3"),
      "firstName" : "Sailaja",
      "lastName" : "PTR",
      "active" : true
}





 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment