Home> Database> MongoDB> body text

Best way to store date/time in MongoDB?

王林
Release: 2023-08-28 18:57:02
forward
993 people have browsed it

在 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();
Copy after login

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

new ISODate();
Copy after login

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") }
Copy after login

Second method:

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

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

> db.ProductsInformation.find().pretty();
Copy after login

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") }
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!