Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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. In the second approach, you can use ISODate(). Both methods store dates in MongoDB's native BSON Date type, ensuring optimal performance for date-based operations.
Syntax
For Date object ?
new Date();
For ISODate ?
new ISODate();
Method 1: Storing Date/Time Using Date Object
To understand the above syntax, let us create a collection with documents using the first approach. The query to create a collection with document is as follows ?
db.ProductsInformation.insertOne({
"ProductId": "Product-1",
"ProductDeliveryDateTime": new Date()
});
The output is ?
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ec6786fd07954a4890686")
}
Method 2: Storing Date/Time Using ISODate
The second approach using ISODate() ?
db.ProductsInformation.insertOne({
"ProductId": "Product-2",
"ProductDeliveryDateTime": new ISODate()
});
The output is ?
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ec6846fd07954a4890687")
}
Verify Result
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")
}
Key Benefits
Both approaches store dates in MongoDB's native BSON Date type, which provides several advantages:
- Time zone handling: Dates are stored in UTC format internally
- Query efficiency: Built-in support for date range queries and sorting
- Consistency: Both Date() and ISODate() create the same BSON Date type
- Index support: Date fields can be indexed for faster query performance
Conclusion
Both new Date() and new ISODate() are functionally equivalent for storing date/time in MongoDB. They both create BSON Date objects stored in UTC format, making them ideal for date-based operations, queries, and indexing.
