For Date field, don't save milliseconds in MongoDB

Hi All,
I have a back-end service developed using .Net Core 3.1. My backend is connected to MongoDB Atlas. In my DB schema, we have a few “Date” fields. These Date fields are being saved till milliseconds precision in Mongo DB like “yyyy-MM-dd T HH:mm:ss.ffff”.

Now we want to truncate these Date fields and save them only till second precision, NOT milliseconds precision. I tried from backend service by converting date format to “yyyy-MM-dd HH:mm:ss” and sending it to Mongo DB. Mongo DB is still saving till milliseconds precision like “yyyy-MM-dd T HH:mm:ss.0000”, it is saving milliseconds as “0000”

Is it possible to truncate milliseconds precision in Date Fields while saving them in MongoDB?

Hi @Tejasvi_Penumarthi,

The BSON Date type is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). As you have mentioned, it is possible to truncate when setting values but the underlying Date precision will always be milliseconds. You can also format to appropriate precision on display and manipulate with aggregation Date Expression Operators.

Can you provide more detail on your use case for removing milliseconds?

An alternative would be to save a 32-bit Unix time value (seconds since the epoch), but 64-bit dates are recommended for future proofing and representing dates in the far future (or past). For more details, see The 2038 problem and how to solve it for MongoDB.

If you have a value that represents a date you can use $toDate (aggregation) to convert supported values but this will not be the most convenient (or efficient) approach for working with dates.

Regards,
Stennie

Hi @Stennie_X

Thank you for your reply. I really appreciate it.

My Use Case:
We have a user profile collection saved in Mongo DB. In the User Profile Collection Schema, we have ‘profileCreatedDate’ and ‘profileUpdatedDate’. Our back-end system is .Net core 3.1 Web API. We are using Mongo DB drivers and Bson Drivers to do CRUD operations with Mongo DB Atlas.

Whenever a user profile is created or updated, we are inserting or updating the current EST time as ‘profileCreatedDate’ and ‘profileUpdatedDate’ respectively. Mongo DB Drivers are automatically converting this EST time to UTC time and saving them in Mongo DB with Milliseconds precision.

We want to keep the Date fields as 64 bit only but want to restrict Date-time values to seconds precision so that our Index size and DB size will be optimal.

You mentioned underlying data precision will always be milliseconds.,
Does it mean, Date Fields will be always be saved in milliseconds precision in Mongo DB?

Regards,
Tejasvi.