mongo fixing broken timestamps

convert bson timestamp to date#

So I’m used to create a timestamp for logging in the db when something is created. What should go wrong with using mongo bson timestamp. Let me say it this way. As long as you leave it alone in the database it will happily coexist with all the other stuff.

But if you want to use it in javascript it gets complicated.

What is a timestamp in bson

This internal timestamp type is a 64 bit value where:

  • the most significant 32 bits are a time_t value (seconds since the Unix epoch)
  • the least significant 32 bits are an incrementing ordinal for operations within a given second.

Of course we can parse it to date, but do we really want to respect this every time we look at a timestamp? So how to reverse it back to good old handy bson date:

Solution

{
  "changed" : { $toDate : { $dateToString : { date: "$created_on"}}}
}

Sometimes it is good to understand the docs, at least now I do:

The BSON timestamp type is for internal MongoDB use. For most cases, in application development, you will want to use the BSON date type. See Date for more information.

further reading#