mongodb

Timestamp in MongoDB


I am looking to use Timestamp in MongoDB by tacking created and updated item.

As far as I know, Timestamp is one option but you can also use Date, ISODate and I don't know which one to use.

I started with Timestamp and when I run a query in mongo shell I get the following output "created" : Timestamp(1642888187, 1)

When I query this timestamp with the help of mongodb nom module, the result I get back is created: { '$timestamp': '7056151034149732353' } and those two values are different and 7056151034149732353 is not a timestamp.

Kind of confused what to use here. Should I stick with ISODate or Timestamp? Though from what I read Timestamp has some advantages but not sure if those advantages will work for my "learning" app but I want to understand the differences.

But if you can show me to get a date from created: { '$timestamp': '7056151034149732353' } that would be helpful too!

Thank you


Solution

  • The BSON type Timestamp is a 64-bit value consisting of a 32-bit epoch timestamp and a 32-bit counter. It is internally used by MongoDB for logical ordering of operations when millisecond or even microsecond resolution is not good enough.

    The value 7056151034149732353 is a 64-bit integer, in hexadecimal that is 0x61ec7bfb00000001.

    Split that into 32-bit values and you get: 0x61ec7bfb = 1642888187 0x00000001 = 1

    Note that because it uses a 32-bit value for seconds since epoch, this datatype is subject to overflowing in the year 2038.

    The ISODate type is a 64-bit value that indicates milliseconds since epoch.

    If knowing the created and updated time to the nearest millisecond is sufficient for the purpose you have in mind, this datatype will suffice, and will not be subject to overflow for the foreseeable future.