MongoDB - ObjectId

We have used the MongoDB object ID in all previous chapters. In this chapter, we will understand the ObjectId structure.
ObjectId is a 12-byte BSON type with the following structure:
- First 4 bytes representing seconds since Unix epoch
- The next 3 bytes are the machine ID
- The next 2 bytes consist of the process ID
- The last 3 bytes are a random counter value
MongoDB uses ObjectIds as the default value of the _id field of each document, which is generated when any document is created. The complex combination of ObjectId makes all _id fields unique.
Creating a new ObjectId
To create a new ObjectId, use the following code −
> newObjectId = ObjectId ()
The above statement returned the following uniquely generated id −
ObjectId ( "5349b4ddd2781d08c09890f3" )
Instead of MongoDB generating ObjectId, you can also provide a 12 byte ID −
> myObjectId = ObjectId ( "5349b4ddd2781d08c09890f4" )
Creating a Document Timestamp
Because _id ObjectId stores a 4-byte timestamp by default, in most cases you don't need to store the creation time of any document. You can get 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" )
Convert ObjectId to String
In some cases, you may need the ObjectId value in string format. To convert an ObjectId to a string, use the following code −
> newObjectId . str
The above code will return the Guid string format −