English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MongoDB ObjectId

In the previous chapters, we have been using MongoDB object Id. In this chapter, we will learn about the structure of ObjectId.

ObjectId is a12byte is the BSON type, with the following structure-

  • The previous4bytes represent the number of seconds since the Unix epoch

  • The next3bytes are the machine identifier

  • The next2a byte is composed of the process id

  • Finally3a byte is a random counter value

MongoDB uses ObjectIds as_idThe default value of each document field, which is generated when any document is created. The complex combination of ObjectId makes all _id fields unique.

Create a new ObjectId

To generate a new ObjectId, please use the following code-

>newObjectId = ObjectId()

The above statement returns the following unique generated id-

ObjectId("5349b4ddd2781d08c09890f3")

In addition to providing MongoDB-generated ObjectId, you can also provide12Byte ID-

>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")

Timestamp of document creation

Since _id ObjectId is stored by default4Byte timestamp, so in most cases, you do not need to store the creation time of any document. You can use the getTimestamp method to get the creation time of the document-

>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 a string format ObjectId value. To convert ObjectId to string, use the following code-

>newObjectId.str

The following code will return the Guid in string format-

5349b4ddd2781d08c09890f3