Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can mongodb handle ObjectId timestamp beyond Tue, 19 Jan 2038?

As per MongoDB official docs, it states that:

ObjectId values consists of 12-bytes, where the first four bytes are a timestamp that reflect the ObjectId’s creation, specifically:

  • a 4-byte value representing the seconds since the Unix epoch,
  • a 3-byte machine identifier,
  • a 2-byte process id, and
  • a 3-byte counter, starting with a random value.

I'm just wondering what's gonna happen on Tue, 19 Jan 2038 03:14:08 GMT when the unix time will be equal to 2147483648 which doesn't fit the 4-byte timestamp in ObjectId *philosoraptor meme*

like image 935
Basim Hennawi Avatar asked Feb 07 '17 18:02

Basim Hennawi


People also ask

How long is MongoDB ObjectId?

ObjectId values are 12 bytes in length, consisting of: A 4-byte timestamp, representing the ObjectId's creation, measured in seconds since the Unix epoch. A 5-byte random value generated once per process. This random value is unique to the machine and process.

Is MongoDB ObjectId incremental?

MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents.

How does MongoDB ObjectId work?

ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document. ObjectID can be considered globally unique for all practical purposes. ObjectID encodes the timestamp of its creation time, which may be used for queries or to sort by creation time.

How does MongoDB generate ObjectId?

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. The 5 byte "random value" does not appear to be random.


1 Answers

Unsigned 2,147,483,648 perfectly fits into 4 bytes. 4 bytes is enough to hold values up to 4,294,967,295, which is a unix epoch for Sunday, 7 February 2106 06:28:16 GMT.

If ObjectID's survive without changes till then, the timestamp part will start from 0, if you care:

> new Date();
ISODate("2106-02-08T12:41:20.450Z")

> db.t.insert({welcome:"from the future"});
WriteResult({ "nInserted" : 1 })

> db.t.find().pretty();
{
    "_id" : ObjectId("0001a7b306c389186a3a9323"),
    "welcome" : "from the future"
}

> db.t.find()[0]._id.getTimestamp();
ISODate("1970-01-02T06:07:47Z")
like image 106
Alex Blex Avatar answered Oct 13 '22 01:10

Alex Blex