Docs Menu

ObjectId

On this page

  • Description
  • Methods and Attributes
  • Examples
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 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 is:

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

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.

Tip
See also:
Give Feedback
MongoDB logo
© 2021 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.