What is ObjectID in MongoDB?

ObjectID is one of the datatypes of MongoDB. Each document is assigned with autogenerated ObjectID with Field_id. An ObjectId is a 12-byte BSON type. The first 4 bytes represent the seconds since the unix epoch. The next 3 bytes consist of the process id. The last 3bytes are a random counter value. We can create a new ObjectID. To generate an ObjectID:

newObjectID=ObjectId()

We know _id objectID by default stores the 4-byte timestamp, in most cases you do not need to store the creation time of any document. You can fetch the creation time of a document using the getTimestamp method.

ObjectId(ā€œ5349b4ddd2781d08c09890f4ā€).getTimestamp()

This will return the creation time of this document in ISO date format.

ISODate(ā€œ2014-04-12T21:49:17Zā€)

In some cases, you may need the value of ObjectID in a string format. To convert the ObjectId into the string, Use the following code

newObjectId.str

The above code will return the string format

5349b4ddd2781d08c09890f3