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

偶尔善良 提交于 2019-12-05 04:32:58

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. This way, a lot of date operations are provided. I.e.

  • new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.

  • new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.

  • new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.

  • new Date(<integer>) specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.

And even more, internally, date objects are stored as a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).

As mentioned in comments its almost depends on your final target. I would suggest you to use MongoDate because it's native format for dates in MongoDB and will keep things intuitive for other developers. And the native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.

Plus, the date of birth "1990-05-21" is stored as "1990-05-20T23:00:00Z" (the day before)

I think that this happens just because timezone on your server is UTC+1. You can manually set the timezone to UTC before saving to DB and it will solve your problem.

AlexZeDim

That's an interesting question and it can't be easily answered. As @Andrey Degtyaruk already noticed it's all about purpose of these datas.

In my case I solve almost the same problem something like these:

store time like a YYYYMMDD string

but, a bit different way. Because "timestamp" field is already reserved by MongoDB (according to BSON docs) I convert date to timestamp (you could use one of these js scripts if you're interested) and store it in DB as "lastModified":"Number".

I'm not sure that my method could be relevant in your Date-of-Birth case, but it's still a way and you could try it.

I was looking for the best solution to this problem as well, and while reading these answers I thought that the simplest solution which would ignore time and thus timezone shifts, yet still allow comparisons and queries on a persons age etc. would be to use an integer format along the lines of YYYYMMDD.

So for birth date 12 March 1980, this would be saved as integer 19800312.

Then I found this plugin for Mongoose, which does more or less that: https://github.com/boblauer/mongoose-dateonly

Only drawback is that you'd have to use DateOnly directly if you want to use the aggregate framework.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!