Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
MongoDB Date.now() format different from new Date(string) format

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!