ObjectId

Description

  • ObjectId()
  • Returns a new ObjectId value. The 12-byte ObjectIdvalue consists of:

    • a 4-byte value representing the seconds since the Unix epoch,
    • a 5-byte random value, and
    • a 3-byte counter, starting with a random value.ObjectId() can accept the following parameter:

FieldTypeDescriptionhexadecimalStringOptional. Hexadecimal string value for the new ObjectId.

Methods and Attributes

ObjectId() has the following attribute and methods:

Attribute/MethodDescription
strReturns 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 stringliteral “ObjectId(…)”.
ObjectId.valueOf()Returns the representation of the object as a hexadecimalstring. The returned string is the str attribute.

Examples

Generate a New ObjectId

To generate a new ObjectId, use ObjectId() with no argument:

  1. x = ObjectId()

In this example, the value of x would be:

  1. ObjectId("507f1f77bcf86cd799439011")

Specify a Hexadecimal String

To generate a new ObjectId using ObjectId() with a uniquehexadecimal string:

  1. y = ObjectId("507f191e810c19729de860ea")

In this example, the value of y would be:

  1. ObjectId("507f191e810c19729de860ea")

Access the Hexadecimal String

Access the str attribute of an ObjectId() object, as follows:

  1. ObjectId("507f191e810c19729de860ea").str

This operation will return the following hexadecimal string:

  1. 507f191e810c19729de860ea

See also

ObjectId BSON Type