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


To update, use update() in MongoDB. To set it to current date, you need to get the current date −

var todayDate = new Date();

Let us first create a collection with documents −

> db.demo644.insertOne({"ShippingDate":new ISODate("2018-04-19")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c76896c954c74be91e6e6")
}
> db.demo644.insertOne({"ShippingDate":new ISODate("2019-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c76966c954c74be91e6e7")
}

Display all documents from a collection with the help of find() method −

> db.demo644.find();

This will produce the following output −

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

Following is the query to update timestamp −

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

Display all documents from a collection with the help of find() method −

> db.demo644.find();

This will produce the following output −

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

Updated on: 12-May-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements