I've read a lot about how to store simple dates (without time) in MongoDB, but I still can't find an answer. Some say to store theme like MongoDate (date + utc time), some say to store theme like a YYYYMMDD string, and some like other funny ways. The rightest way seems to be MongoDate, but why should I store a date of birth as a date with UTC time?
Plus, the date of birth "1990-05-21" is stored as "1990-05-20T23:00:00Z" (the day before): this date shouldn't change depending on timezone, but remain the same world wide.
I'm still wondering why MongoDB doesn't provide a simple "date" type, as all the other databases do.
Simply use: new Date("<YYYY-mm-dd>"); Which returns the ISODate with the specified date without a timestamp. MongoDB uses the ISO-8601 date notation, to represent date objects.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
The DATE type in MongoDB can store date and time values as a combined unit. The BSON Date type is a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).
MongoDB will treat them as they are - string data type. And, the string comparison rules will apply. You can safely store dates as strings and query on them as long as they are properly formatted for date, i.e., “YYYY-MM-ddTHH:mm:ss”.
Store it as a simple string "1985-21-07". It might sound counter-intuitive and light up your red "database types" bulb, but saving a date of birth as a Date() brings to the table many "parts" (hours, minutes, seconds...) that don't mean anything and will cause headache and be error-prone when saving and getting birth dates in and out of mongo.
Read the highest answer here (NOT THE ONE MARKED AS CORRECT): What is the best way to store dates in MongoDB?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With