All about ObjectId in MongoDB.

April 24, 2024 / 10 mins read
object id in mongodb

ObjectId is mainly used with _id field in MongoDB. ObjectId() gives unique value each time.So we can use it as primary key in collection.

Even if we pass any other data type for _id field then also it work as primary key in collection.But one think we need to keep in mind that same value should not be used with another document in same collection.

What is ObjectId() ?

We saw many times the value of _id is something like this

ObjectId('6626fe516548c947e716c9b9')

By looking at string value we will believe like it is some random 24 character UUID or any randomly generated value.

But this is not true, ObjectId follow some rules to create objectId. Let's see what are those

What actually contains in ObjectId() ?

ObjectId() contains 24 character. And size of ObjectId() is 12 byte.
From 12 Bytes, 4 bytes is for seconds from Unix Epoch, 5 byte of random value generated from machine and process and remaining 3 bytes are of incrementing counter which is initialized to random value

As we know that ObjectId contains the timestamp, if _id field is not passed at time of inserting document then mongoDB will automatically add _id field in document. And for that _id field it will use objectId() which contains current timestamp as first 4 byte portion.

If our _id field storing ObjectId() then we can extract timestamp from it.

db.collection.findOne({},{_id:1})

Constructors for ObjectId()

Syntax

ObjectId(<value>)
value can be a hexadecimal string or integer value(second from UNIX Epoch).

Examples:

1. Passing hexadecimal value for ObjectId()

db.collection.insertOne({_id:ObjectId('662860e16548c947e716c9bb'),name:"Codediggy Hexadecimal"})
We can confirm that ObjectId with given hexadecimal value is inserted or not using find Query
db.collection.findOne({})

2. Passing integer value for ObjectId()

Passed integer value is added as second in UNIX Epoch time.
Note: Passed integer value is not added in current timestamp.
We are passing 59, so it will add 59 seconds to Unix Epoch time.

db.collection.insertOne({_id:ObjectId(59),name:"Codediggy Integer"})

We can confirm that ObjectId with given integer value is inserted or not using find Query

db.collection.findOne({"name":"Codediggy Integer"})

Methods of ObjectId

1.getTimestamp()

As we discussed above that object contains 4 bytes of times in second from unix epoch, so we can extract that time from object id using getTimestamp().

ObjectId('66299a8a6548c947e716c9c6').getTimestamp()

It will return the timestamp of creation of objectId

ISODate('2024-04-24T23:49:30.000Z')
2.toString()

toString() returns string representation of ObjectId

ObjectId('66299a8a6548c947e716c9c6').toString()

It will return the hexadecimal as string

66299a8a6548c947e716c9c6
3. ObjectId.createFromBase64()

ObjectId.createFromBase64() is used to create object Id from base 64 text.

var id = ObjectId.createFromBase64('aGkgQ29kZWRpZ2d5')

We passed base 64 text aGkgQ29kZWRpZ2d5 to method for creating object Id using it.
Note: If we use getTimestamp() on ObjectId's those are created from base64, those ids will not return timestamp as their creation time. Time returned by method will be different.

We can again get base64 text from ObjectIds those are created using base64

var id = ObjectId.createFromBase64('aGkgQ29kZWRpZ2d5')
Buffer(id.toString(),'hex').toString('base64')

Note: The length of base64 text passing to method should be 16 characters.

4.ObjectId.createFromHexString()

ObjectId.createFromHexString() return ObjectId created using hexadecimal strign passed to method.

ObjectId.createFromHexString('66299a8a6548c947e716c9c6')

MongoDB

ObjectId

ObjectId Methods

Discover more