Friday, 4 June 2021

MongoDB: updateMany: Update multiple documents

‘updateMany()’ method is used to update all the documents that satisfy given filter criteria.

 

Syntax

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

 

Example

db.employee.updateMany({"lastName" : "Gurram"}, {$set : {"active": false, "modifiedTime" : Date.now()}})

 

Let’s experiment with employee collection.

> db.employee.find()
{ "_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 }

 

For example, set the active property of all the employees whose lastName is Gurram to false and add modifiedTime property with current time stamp.

> db.employee.updateMany({"lastName" : "Gurram"}, {$set : {"active": false, "modifiedTime" : Date.now()}})
{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }
> 
>
>
> db.employee.find()
{ "_id" : ObjectId("60baff65baf44d88348459bf"), "firstName" : "Krishna", "lastName" : "Gurram", "active" : false, "modifiedTime" : 1622868537108 }
{ "_id" : ObjectId("60baff6dbaf44d88348459c0"), "firstName" : "Ram", "lastName" : "Gurram", "active" : false, "modifiedTime" : 1622868537108 }
{ "_id" : ObjectId("60baff75baf44d88348459c1"), "firstName" : "Thulasi", "lastName" : "Gurram", "active" : false, "modifiedTime" : 1622868537108 }
{ "_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