- Reference >
mongoShell Methods >- Object Constructors and Methods >
- ObjectId
ObjectId¶
On this page
Description¶
-
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
- 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.
ObjectId()can accept the following parameter:Field Type Description hexadecimalString Optional. Hexadecimal string value for the new ObjectId.
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 would be:
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:
See also