- Reference >
mongosh
Methods >- Object Constructors and Methods >
- ObjectId
ObjectId¶
On this page
Description¶
-
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 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 :wikipedia:`Unix epoch` to create the new timestamp.
Methods and Attributes¶
ObjectId()
has the following attribute and methods:
Attribute/Method | Description |
---|---|
str |
Returns the hexadecimal string representation of the object. |
ObjectId.getTimestamp() |
Returns the timestamp portion of the object as a Date. |
ObjectId.toString() |
Returns the JavaScript representation in the form of a string
literal “ObjectId(...) ”. |
ObjectId.valueOf() |
Returns the representation of the object as a hexadecimal
string. The returned string is the str attribute. |
Examples¶
Generate a New ObjectId¶
To generate a new ObjectId, use ObjectId()
with no argument:
In this example, the value of x
is:
Specify a Hexadecimal String¶
To generate a new ObjectId using ObjectId()
with a unique
hexadecimal string:
In this example, the value of y
would be:
Access the Hexadecimal String¶
Access the str
attribute of an ObjectId()
object, as follows:
This operation will return the following hexadecimal string:
Specify an Integer String¶
Generate a new ObjectId using an integer.
The ObjectId resembles:
The first four bytes of the ObjectId are the number of seconds since
the :wikipedia:`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