Home  >  Article  >  Database  >  Best way to store date/time in MongoDB?

Best way to store date/time in MongoDB?

王林
王林forward
2023-08-28 18:57:021059browse

在 MongoDB 中存储日期/时间的最佳方式?

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

new Date();

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

new ISODate();

To understand the above syntax, let us follow the first method to create a collection containing documents. The query to create a collection using documents is as follows:

First method:

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

Second method:

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

Display all documents in the collection with the help of the 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 to use a Date object.

The above is the detailed content of Best way to store date/time in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete