Docs Menu

ObjectId()

ObjectId(<hexadecimal>)

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

  • a 4-byte timestamp value, 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, with the most significant bytes appearing first in the byte sequence.

You can use ObjectId() for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

ObjectId() can accept one of the following inputs:

Input Type
Description
hexadecimal
Optional. A 24 character hexadecimal string value for the new ObjectId.
integer
Optional. The integer value, in seconds, is added to the Unix epoch to create the new timestamp.

ObjectId() has the following attribute and methods:

Attribute/Method
Description
str
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 would be:

ObjectId("507f1f77bcf86cd799439011")

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

y = ObjectId("507f191e810c19729de860ea")

In this example, the value of y would be:

ObjectId("507f191e810c19729de860ea")

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

ObjectId("507f191e810c19729de860ea").str

This operation will return the following hexadecimal string:

507f191e810c19729de860ea

Tip

See also: