Best way to Store Date and time in MongoDB

Best way to Store Date and time in MongoDB

It is often confusing for MongoDB beginners to store date and time. Some peoples decide to use timestamps BUT there is a much better way to store date and time in MongoDB.

The database is not meant to human reading but it is great to store is a format which is convenient and in human-readable form.

Let me tell you that migrating database from one date format to another is a nightmare. If the application is complex you will also experience nasty bugs. So it is important to perfectly plan date-time management in your application.

I migrated a Node.js application from timestamps and it took me about 10 days to find and fix bugs (mostly date conversions).

The best format to store date and time

The best format to store date and time in MongoDB is native javascript Date() or ISO date format as it internally converts it into BSON native Date object.

The official MongoDB docs say about BSON native date object:

BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). This results in a representable date range of about 290 million years into the past and future.

At first, the definition may look like timestamps but BSON Timestamps and BSON Date are different.

MongoDB officially recommends to store the date in BSON Date object and avoid timestamps if possible as it is for internal use.

MongoDB BSON Date Object vs Timestamp

At first, the BSON native date object definition may look like a timestamp. But they are different.

Timestamps in MongoDB are mostly for the internal purpose and they are 64-bit value.

The most significant 32 bits are time_t which is seconds since UNIX epoch. The least significant 32 bits are incremental ordinal for operations.

The BSON Date object milliseconds passed since 1 Jan 1970 (UNIX epoch) with the date range of 290 million years past and future.

Examples to insert Date in MongoDB

In real-world cases, we mostly use MongoDB in MERN Stack. If this is your case then you can easily insert new Date() into the database.

Here is the MongoDB shell syntax to insert date.

db.posts.insert({title: "How to Insert Date in MongoDB", time: new Date()})

Or we can also use.

db.posts.insert({title: "How to Insert Date in MongoDB", time: new ISODate()})

The benefits of using native date object is that it supports many useful methods for conversion which are very helpful and reduce complexity.

Share the Post ;)

Related Posts