What is ObjectId in MongoDB?

Prashant Gangwar
2 min readOct 18, 2021

ObjectIds are small, likely unique, fast to generate, and ordered.

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.

It can be of length 24 byte hex string, 12 byte binary string.

How ObjectId calculated in MongoDB?

ObjectId values are 12 bytes in length, MongoDB driver generates ObjectId automatically if omit from document data which consist of the following :

  • a 4-byte timestamp value, representing the ObjectId’s creation, measured in seconds since the Unix epoch(which will not run out of seconds until the year 2106)
  • a 5-byte random value generated once per process. This random value is unique to the machine and process. ( consist of 3 byte machine id — usually derived by MAC address and 2 byte process id)
  • a 3-byte incrementing counter, initialized to a random value

While the BSON format itself is little-endian, the timestamp and counter values are big-endian, with the most significant bytes appearing first in the byte sequence.

How to get the timestamp from ObjectID?

ObjectId(“507c7f79bcf86cd7994f6c0e”).getTimestamp() this will return the following output:
ISODate("2012-10-15T21:26:17Z")

You can refer official MongoDB article about ObjectId by the following link:

https://docs.mongodb.com/manual/reference/method/ObjectId/#mongodb-method-ObjectId

Hope this articles helped you to understand the MongoDB ObjectId.

--

--

Prashant Gangwar

Technical Lead focused on backend services, micro services, enthusiastic for new tech skills