Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to store dates of birth in MongoDB?

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.

like image 810
Drew Avatar asked Apr 21 '17 10:04

Drew


People also ask

How does MongoDB store date of birth?

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.

What is the best way to store date in MongoDB?

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.

Can we store date in MongoDB?

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).

Can I store date as string in MongoDB?

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”.


1 Answers

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?

like image 111
Yaron Levi Avatar answered Sep 17 '22 16:09

Yaron Levi