Best way to store date/time in MongoDB?


There are two different ways by which you can store date/time in MongoDB. In the first approach, you can use Date objects like JavaScript. The Date object is the best way to store date/time in MongoDB. The syntax is as follows:

new Date();

In the second approach, you can use ISODate(). The syntax is as follows:

new ISODate();

To understand the above syntax, let us create a collection with documents following the first approach. The query to create a collection with document is as follows:

The first approach:

> db.ProductsInformation.insertOne({"ProductId":"Product-1","ProductDeliveryDateTime":new
Date()});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ec6786fd07954a4890686")
}

The second approach:

> db.ProductsInformation.insertOne({"ProductId":"Product-2","ProductDeliveryDateTime":new
ISODate()});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ec6846fd07954a4890687")
}

Display all documents from the collection with the help of find() method. The query is as follows:

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

The following is the output:

{
   "_id" : ObjectId("5c6ec6786fd07954a4890686"),
   "ProductId" : "Product-1",
   "ProductDeliveryDateTime" : ISODate("2019-02-21T15:40:40.901Z")
}
{
   "_id" : ObjectId("5c6ec6846fd07954a4890687"),
   "ProductId" : "Product-2",
   "ProductDeliveryDateTime" : ISODate("2019-02-21T15:40:52.684Z")
}

Note: The best way to store date/time objects is with Date object.

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements