How to update a Timestamp and set to current date in MongoDB?

To update a timestamp and set it to the current date in MongoDB, use the update() method with $set operator and JavaScript's new Date() to get the current timestamp.

Syntax

var currentDate = new Date();
db.collection.update(
    {}, 
    { $set: { "timestampField": currentDate } }, 
    { multi: true }
);

Sample Data

Let us first create a collection with documents ?

db.demo644.insertMany([
    { "ShippingDate": new ISODate("2018-04-19") },
    { "ShippingDate": new ISODate("2019-01-10") }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e9c76896c954c74be91e6e6"),
        ObjectId("5e9c76966c954c74be91e6e7")
    ]
}

Display all documents from the collection ?

db.demo644.find();
{ "_id": ObjectId("5e9c76896c954c74be91e6e6"), "ShippingDate": ISODate("2018-04-19T00:00:00Z") }
{ "_id": ObjectId("5e9c76966c954c74be91e6e7"), "ShippingDate": ISODate("2019-01-10T00:00:00Z") }

Example: Update Timestamp to Current Date

Get the current date and update all documents ?

var todayDate = new Date();
todayDate.setHours(todayDate.getHours() + 1);
db.demo644.update({}, {$set: {ShippingDate: todayDate}}, {multi: true});
WriteResult({ "nMatched": 2, "nUpserted": 0, "nModified": 2 })

Verify Result

db.demo644.find();
{ "_id": ObjectId("5e9c76896c954c74be91e6e6"), "ShippingDate": ISODate("2020-04-19T17:04:58.453Z") }
{ "_id": ObjectId("5e9c76966c954c74be91e6e7"), "ShippingDate": ISODate("2020-04-19T17:04:58.453Z") }

Key Points

  • new Date() creates a JavaScript Date object with the current timestamp
  • multi: true option updates all matching documents
  • setHours() method can adjust the timestamp if needed

Conclusion

Use new Date() with the $set operator to update timestamp fields to the current date. The multi: true option ensures all matching documents are updated simultaneously.

Updated on: 2026-03-15T03:15:19+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements