Tech Dive 1: MongoDB's ObjectId

Tech Dive 1: MongoDB's ObjectId

Let's get to know about the ObjectId


2 min read

MongoDB is a famous NoSQL Database. If you're just getting started with MongoDB, I would suggest you begin with Mongo University


MongoDB's ObjectID is made of 12 bytes. The 12 bytes consists of

  • a 4-byte timestamp.

  • a 5-byte random value generated once per process.

  • a 3-byte incrementing counter initialized to a random value.



65f87920 - Unix Epoch Timestamp

068c7d17cb - Random Value

1288d6 - Incrementing Counter

Constructing ObjectId

You can use the ObjectId() method to construct a new ObjectId.

Optionally, it can take two inputs.

  1. hexadecimal - A 24-character hexadecimal string value.

  2. integer - The integer value, in seconds, is added to the Unix epoch to create the new timestamp.


     > ObjectId(10)
     < ObjectId('0000000a0d098c2eda0f296e')

Methods you can use on ObjectId


Movie gif. Rowan Atkinson as Mr. Bean in Mr. Bean's Holiday, stands in a field of yellow flowers on a windy day. He looks off into the distance and then at his watch, before scratching his head.

Since the timestamp is included in the ObjectId, you can retrieve the time in which the ObjectId was generated.

> ObjectId('665377378755af3d1e7c5701').getTimestamp()
< 2024-05-26T17:53:59.000Z

> ObjectId('0000000a0d098c2eda0f296e').getTimestamp()
< 1970-01-01T00:00:10.000Z


You can use this method in case if you want to convert the ObjectId to hexadecimal string.

> ObjectId('665b4d520d098c2eda0f296d').toString()
< 665b4d520d098c2eda0f296d

If you’re a tech enthusiast and resonate with my content, follow me on LinkedIn, GitHub, and Twitter.