We have been using MongoDB Object Id in all the preceding chapters. In this bankruptcy, we can recognize the structure of ObjectId.
An ObjectId is a 12-byte BSON kind having the following shape −
- The first four bytes representing the seconds since the unix epoch
- The next 3 bytes are the machine identifier
- The next 2 bytes consists of technique id
- The last 3 bytes are a random counter fee
MongoDB makes use of ObjectIds because the default fee of _id subject of every document, which is generated whilst the advent of any record. The complicated combination of ObjectId makes all the _id fields specific.
Creating New ObjectId
To generate a new ObjectId use the subsequent code −
>newObjectId = ObjectId()
The above declaration returned the subsequent uniquely generated id −
ObjectId("5349b4ddd2781d08c09890f3")
Instead of MongoDB generating the ObjectId, you could additionally provide a 12-byte identification −
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
Creating Timestamp of a Document
Since the _id ObjectId by means of default shops the four-byte timestamp, in most instances you do now not want to save the creation time of any record. You can fetch the introduction time of a document using getTimestamp method −
>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
This will go back the advent time of this file in ISO date layout −
ISODate("2014-04-12T21:49:17Z")
Converting ObjectId to String
In some instances, you could need the cost of ObjectId in a string format. To convert the ObjectId in string, use the following code −
>newObjectId.str
The above code will go back the string format of the Guid −
5349b4ddd2781d08c09890f3