Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: should I use string instead of date?

In my web project using angular, node and mongodb with JSON, date is not natively supported by JSON serializer. There is a workaround for this problem, as shown here. However, I wonder what's the benefit saving the date as a date object instead of a string in MongoDB? I'm not that far with the project so I don't see the difference.

like image 552
newman Avatar asked Dec 08 '22 03:12

newman


2 Answers

By saving your dates not as dates but as strings, you are missing out on some very useful features:

  1. MongoDB can query date-ranges with $gt and $lt.
  2. In version 3.0, the aggregation framework got many useful aggregation operators for date handling. None of those work on strings and few of them can be adequately substituted by string operators.
  3. MongoDB dates are internally handled in UNIX epoch, so nasty details like saving timestamps from different timezones or daylight saving times are a non-issue.
  4. A BSON Date is just 8 byte. A date in the minimal form of YYYYMMDD is 12 byte (strings in BSON are prefixed with a 4 byte integer for the length). When you store it as an ISODate string which uses all the ISO 8601 standard has to offer (date, time accurate to millisecond and timezone), you have 32 byte - four times the storage space.

You need to know if any of this matters for your project.

When you really want to avoid using the BSON Date type, you should consider to store your dates as a number representing the elapsed milliseconds/seconds/hours/days (whatever appropriate for your use-case) since a fixed point in time instead of a string. That way you retain the advantages of everything but point 2.

like image 75
Philipp Avatar answered Dec 11 '22 11:12

Philipp


You should at least use ISO dates if you go for this approach. I would however argue that there are benefits in storing date values as date objects. Storing dates as date objects will allow you to add indices and should also help with date range queries. Saying this many developers seem to be happy to store dates as strings, see What is the best way to store dates in MongoDB?

like image 35
Alex Avatar answered Dec 11 '22 11:12

Alex