MongoDB's ObjectId Explained

📖 2 min read

Let's get to know MongoDB's ObjectId!

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

Anatomy

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.

Example:

65f87920068c7d17cb1288d6

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.

hexadecimal - A 24-character hexadecimal string value.

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

Example:

$ ObjectId(10)
ObjectId('0000000a0d098c2eda0f296e')

Methods you can use on ObjectId

getTimestamp()

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

toString()

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

$ ObjectId('665b4d520d098c2eda0f296d').toString()
665b4d520d098c2eda0f296d