How to use the ISODate format In MongoDB
MongoDB also allows us to store dates and times using a special format called ISODate. This format follows the ISO 8601 standard for representing dates and times. Using ISODate can be helpful when we need to store dates and times in a specific format or when working with data that follows this standard.
Syntax:
db.ProductsInformation.insertOne({"ProductId":"Product-2","ProductDeliveryDateTime":new ISODate()})
Output:
To view all the documents in the ProductsInformation collection, including the ones we just inserted, we can use the find() method with the pretty() option to format the output:
Final Output:
Explanation:
- The first document has ProductId set to “Product-1” and ProductDeliveryDateTime set to an ISODate value representing the date and time when it was inserted using new Date().
- The second document has ProductId set to “Product-2” and ProductDeliveryDateTime set to an ISODate value representing the date and time when it was inserted using new ISODate(). Both documents have their unique _id values (ObjectIds) automatically generated by MongoDB.
What is the Best Way to Store Date/Time in MongoDB
Accurate storage of date and time is crucial for a wide range of applications, including social media platforms, financial systems, and messaging apps. Properly stored dates enable sequential sorting, date range queries. MongoDB’s flexible schema allows for efficient date/time storage, providing developers with the tools they need to manage temporal data effectively.
In this article, We will learn about What is the Best Way to Store Date/Time in MongoDB along with the practical implementation and so on.