Home >>MongoDB Tutorial >MongoDB ObjectId

MongoDB ObjectId

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-

  • The first 4 bytes after the unix epoch describing the seconds
  • The next 3 bytes are the identifier for the machine.
  • The next 2 bytes are process id id.
  • A random counter value is the last 3 bytes

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.

Creating New ObjectId

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")

Creating Timestamp of a Document

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")

Converting ObjectId to String

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

No Sidebar ads