Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual


On this page

  • Description
  • Methods and Attributes
  • Examples

Returns a new ObjectId. The 12-byte ObjectId consists of:

  • A 4-byte timestamp, representing the ObjectId's creation, measured in seconds since the Unix epoch.

  • A 5-byte random value generated once per process. This random value is unique to the machine and process.

  • A 3-byte incrementing counter, initialized to a random value.

While the BSON format itself is little-endian, the timestamp and counter values are big-endian, the most significant bytes appear first in the byte sequence.

If an integer value is used to create an ObjectId, the integer replaces the timestamp.

ObjectId() can accept one of the following inputs:

Input Type
Optional. A 24 character hexadecimal string value for the new ObjectId.

ObjectId() has the following attribute and methods:

Returns the hexadecimal string representation of the object.
Returns the timestamp portion of the object as a Date.
Returns the JavaScript representation in the form of a string literal "ObjectId(...)".
Returns the representation of the object as a hexadecimal string. The returned string is the str attribute.

To generate a new ObjectId, use ObjectId() with no argument:

x = ObjectId()

In this example, the value of x is:


To generate a new ObjectId using ObjectId() with a unique hexadecimal string:

y = ObjectId("507f191e810c19729de860ea")

In this example, the value of y would be:


Access the str attribute of an ObjectId() object, as follows:


This operation will return the following hexadecimal string:


Generate a new ObjectId using an integer.

newObjectId = ObjectId(32)

The ObjectId resembles:


The first four bytes of the ObjectId are the number of seconds since the Unix epoch. In this example 32 seconds, represented in hexadecimal as 00000020, are added. A five byte random element and a three byte counter make up the rest of the ObjectId.


See also:

←  Date()ObjectId.getTimestamp() →