Friday 4 June 2021

MongoDB: updateMany: Update all the documents

Passing filter criteria as empty object, you can match to all the documents.

 

Example

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

 

Let’s experiment with employee collection.

> db.employee.find().pretty()
{
      "_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("60bb035bbaf44d88348459c5"),
      "firstName" : "Sailja",
      "lastName" : "PTR",
      "active" : true,
      "modifiedTime" : 1622868827180
}

 

Set active flag to true and modifiedTime to current time stamp for all the documents in the collection.

> db.employee.updateMany({}, {$set : {"active" : true, "modifiedTime": Date.now()}})
{ "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 4 }
> 
> 
> db.employee.find().pretty()
{
      "_id" : ObjectId("60baff65baf44d88348459bf"),
      "firstName" : "Krishna",
      "lastName" : "Gurram",
      "active" : true,
      "modifiedTime" : 1622868890184
}
{
      "_id" : ObjectId("60baff6dbaf44d88348459c0"),
      "firstName" : "Ram",
      "lastName" : "Gurram",
      "active" : true,
      "modifiedTime" : 1622868890184
}
{
      "_id" : ObjectId("60baff75baf44d88348459c1"),
      "firstName" : "Thulasi",
      "lastName" : "Gurram",
      "active" : true,
      "modifiedTime" : 1622868890184
}
{
      "_id" : ObjectId("60bb035bbaf44d88348459c5"),
      "firstName" : "Sailja",
      "lastName" : "PTR",
      "active" : true,
      "modifiedTime" : 1622868890184
}

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment