How can I save new Date() in MongoDB?


To save new Date() in MongoDB, you can use new ISODate(). Let us create a collection with documents −

> db.saveDateDemo.insertOne({"UserName":"John","UserLoginDatetime":new ISODate('2018-01-31 12:34:56')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd67d4de8cc557214c0e04")
}
> db.saveDateDemo.insertOne({"UserName":"John","UserLoginDatetime":new ISODate('2019-02-01 04:01:10')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd67e8de8cc557214c0e05")
}
> db.saveDateDemo.insertOne({"UserName":"John","UserLoginDatetime":new ISODate('2019-04-22 12:36:45')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd6805de8cc557214c0e06")
}

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

> db.saveDateDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cbd67d4de8cc557214c0e04"),
   "UserName" : "John",
   "UserLoginDatetime" : ISODate("2018-01-31T12:34:56Z")
}
{
   "_id" : ObjectId("5cbd67e8de8cc557214c0e05"),
   "UserName" : "John",
   "UserLoginDatetime" : ISODate("2019-02-01T04:01:10Z")
}
{
   "_id" : ObjectId("5cbd6805de8cc557214c0e06"),
   "UserName" : "John",
   "UserLoginDatetime" : ISODate("2019-04-22T12:36:45Z")
}

Updated on: 30-Jul-2019

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements