I'm struggling to understand the logic behind MongoDB date formatting, if I save a field like so:
date: Date.now()
in the database looks like:
date: 1633186879027
I have a date like 2021-08-27T19:00:38.000+00:00 , and I save it like so:
date: "2021-08-27T19:00:38.000+00:00"
in the database looks like:
date: "2021-08-27T19:00:38.000+00:00"
and it's not what I want cause it's a string and I can't sort stuff by date then.
so i tried to save it like so:
date: new Date("2021-08-27T19:00:38.000+00:00")
and in the database looks like:
date: 2021-08-27T19:00:38.000+00:00
without brakets, as Mongodb does for strings, so must not be a string either
how am I supposed to save it so that it looks like the first one (1633186879027)?
because I then need to sort stuff by date and I think that's the correct format to use?
MongoDB stores data using BSON. The definition is here
A datetime is stored as the number of milliseconds since 1970-01-01 using a 64-bit integer.
Date.now() returns an integer, so the sample data would be stored as BSON type \x12 with the value 1633186879027.
new Date("2021-08-27T19:00:38.000+00:00") would be stored as BSON type \x09 with the value 1630090838000.
The output date: 2021-08-27T19:00:38.000+00:00 was generated by the driver or application on the client side after it was retrieved.
MongoDB directly support sorting on dates.
Also note that if you have dates stored as strings like "2021-08-27T19:00:38.000+00:00", a lexicographical sort of those string would put them in chronological order.