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:


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.


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


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


The above code will return the string format