Docs Home → Develop Applications → MongoDB Manual
ObjectId![](/docs/v5.3/assets/link.svg)
On this page
Description![](/docs/v5.3/assets/link.svg)
ObjectId(<value>)
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 TypeDescriptionhexadecimal
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.
Methods and Attributes![](/docs/v5.3/assets/link.svg)
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. |
Examples![](/docs/v5.3/assets/link.svg)
Generate a New ObjectId![](/docs/v5.3/assets/link.svg)
To generate a new ObjectId, use ObjectId()
with no argument:
x = ObjectId()
In this example, the value of x
is:
ObjectId("507f1f77bcf86cd799439011")
Specify a Hexadecimal String![](/docs/v5.3/assets/link.svg)
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 Hexadecimal String![](/docs/v5.3/assets/link.svg)
Access the str
attribute of an ObjectId()
object, as follows:
ObjectId("507f191e810c19729de860ea").str
This operation will return the following hexadecimal string:
507f191e810c19729de860ea
Specify an Integer String![](/docs/v5.3/assets/link.svg)
Generate a new ObjectId using an integer.
newObjectId = ObjectId(32)
The ObjectId resembles:
ObjectId("00000020f51bb4362eee2a4d")
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.