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.
For timestamp and counter values, the most significant bytes appear first in the byte sequence (big-endian). This is unlike other BSON values, where the least significant bytes appear first (little-endian).
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
ObjectId()
has the following methods:
Methods | Description |
---|---|
Returns the timestamp portion of the object as a Date. | |
Returns the ObjectId as a hexadecimal string. | |
Returns ObjectId.self . |
Behavior
Starting in MongoDB 5.0, mongosh
replaces the legacy mongo
shell. The ObjectId()
methods work differently in mongosh
than
in the legacy mongo
shell. For more information on the legacy
methods, see Legacy mongo Shell.
Examples
Generate a New ObjectId
To generate a new ObjectId, use ObjectId()
with no argument:
newObjectId = ObjectId()
In this example, the value of newObjectId
is:
ObjectId("507f1f77bcf86cd799439011")
Return a Hexadecimal String
To return the ObjectId as a hexadecimal string, use the toString()
method.
ObjectId("507f191e810c19729de860ea").toString()
The method returns:
507f191e810c19729de860ea
Specify an Integer String
If you want to adjust the ObjectId timestamp, use an integer to generate a new ObjectId.
newObjectId = ObjectId(32)
The ObjectId value resembles:
ObjectId("00000020f51bb4362eee2a4d")
The example ObjectId consists of:
A four byte time stamp,
00000020
A five byte random element,
f51bb4362e
A three byte counter,
ee2a4d
The first four bytes of the ObjectId are the number of seconds since the
Unix epoch. In this example, the ObjectId timestamp is
00000020
which is 32
in hexadecimal.
Specify a Hexadecimal String
If you want to use a hexadecimal string to specify an ObjectId, pass a
unique, 24 character hexadecimal value when you call
ObjectId()
:
newObjectId = ObjectId("507f191e810c19729de860ea")