Home >>MongoDB Tutorial >MongoDB ObjectId
In all the earlier chapters, we used MongoDB Object Id. We are going to understand the structure of ObjectId in this chapter.
An ObjectId is a type of 12-byte BSON with the following structure-
MongoDB uses ObjectIds as the default value of each document's id field, which is provided when any document is created. The complex ObjectId combination makes all of the ID fields distinct.
To generate a new ObjectId use the following code −
>newObjectId = ObjectId()
The above statement returned the following uniquely generated id −
ObjectId("5349b4ddd2781d08c09890f3")
Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id −
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
Since the 4-byte timestamp is stored by default with the _id ObjectId, you do not need to store the development time of any document in most cases. The creation time of a document can be obtained 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")
You can need an ObjectId value in a string format in some cases. Use the following code − to convert an ObjectId to a string.
>newObjectId.str
The above code will return the string format of the Guid −
5349b4ddd2781d08c09890f3