What is ObjectId in MongoDB?

Learn via video courses
Topics Covered

Overview

MongoDB ObjectId is a 12-byte BSON type in MongoDB that uniquely identifies a document in a collection. It is made up of a four-byte timestamp, a random five-byte value generated once per process, and a three-byte incrementing counter with a random value.

  • ObjectId.getTimestamp() returns the MongoDB ObjectId's timestamp as a Date object.
  • ObjectId.toString() returns the ObjectId MongoDb as a string representation.
  • ObjectId.valueOf() returns the same ObjectId MongoDB as the object.
  • str can be used to obtain the MongoDB ObjectId's hexadecimal string representation.

We can also create a new ObjectId MongoDB and use the MongoDB ObjectId methods to extract the timestamp and convert the object to a string format.

Introduction to MongoDB ObjectId

MongoDB ObjectID is a 12-byte, BSON type unique identifier for MongoDB documents. It acts as a primary key for MongoDB documents. The use of ObjectId MongoDB allows for efficient data retrieval and indexing. When a document is inserted, MongoDB generates an ObjectID that can be accessed and used in queries and updates. Custom ObjectIDs can also be generated using the MongoDB ObjectId() method provided by the MongoDB driver.

The 12-byte BSON type ObjectId MongoDB consists of the following components:

  1. A four-byte timestamp that represents the MongoDB ObjectId's creation time in seconds since the Unix epoch. It is useful in sorting and querying objects easily based on their creation time.

  2. A random five-byte value generated once per process that is unique to the machine and process. This makes sure that each ObjectId MongoDB generated is truly unique thus lowering the possibility of duplicates.

  3. A three-byte incrementing counter that is set to a random value and is incremented for each MongoDB ObjectId generated in the same process.

object id

The timestamp and counter values in the ObjectId MongoDB structure are encoded in big-endian format, with the most significant bytes appearing first in the byte sequence. In contrast, other BSON values are usually encoded in little-endian format, with the least significant bytes coming first.

The use of a big-endian byte sequence ensures that the most significant bits of the timestamp and counter values are stored first, making sorting and indexing the MongoDB ObjectId values in a database easier.

If we use an integer to create an ObjectId MongoDB, that integer will replace the timestamp value in the MongoDB ObjectId structure. The ability to create an ObjectId MongoDB from an integer value allows you to generate MongoDB ObjectId values with a specific timestamp, which can be useful in certain scenarios.

Format of MongoDB ObjectId

ObjectId() MongoDB accepts only one parameter. It can accept one of the following inputs:

Input TypeDescription
hexadecimalMongoDB ObjectId is represented as a string of 24 hexadecimal characters. (Optional)
integerThe integer value representing seconds is added to the Unix epoch to create a new timestamp for ObjectId MongoDB. (Optional)

Methods of MongoDB ObjectId

MongoDB ObjectId() has some methods to modify and access data from the ObjectId(). The methods are:

  1. ObjectId.getTimestamp():

    It returns the object's timestamp in the form of a Date. It extracts the timestamp information embedded in the first four bytes of the ObjectId MongoDB and converts it to a date and time format that humans can understand. The year, month, day, hour, minute, second, and time zone offset are all part of the ISO 8601 format for dates and times.

  2. ObjectId.toString():

    It returns the string representation of the MongoDB ObjectId. It returns a hexadecimal string representation of the ObjectId MongoDB. When we need to convert an ObjectId MongoDB to a string to store or send as a value, this method comes in handy.

  3. ObjectId.valueOf():

    It returns the "ObjectId" of the object itself. It is used to generate a new MongoDB ObjectId instance based on a string representation of an ObjectId MongoDB. It only accepts one parameter, which is the string representation of the MongoDB ObjectId. It is useful when we want to work directly with the ObjectId MongoDB object.

  4. ObjectId.str:

    It returns the object's hexadecimal string representation.

MongoDB ObjectId Behavior

The legacy Mongo shell was replaced by a new shell called Mongosh with the release of MongoDB 5.0. The MongoDB ObjectId() methods in Mongosh behave slightly differently than in the legacy Mongo shell.

Similarly to the legacy Mongo shell, the ObjectId MongoDB constructor in Mongosh generates a new ObjectId. When the MongoDB ObjectId() constructor is called without any arguments, Mongosh generates a new random ObjectId MongoDB. The legacy Mongo shell, on the other hand, generates an ObjectId MongoDB based on the current timestamp value.

Furthermore, the MongoDB ObjectId() method in Mongosh returns an ObjectId object, which can be used to call its methods such as getTimestamp(), toString(), and so on. The MongoDB ObjectId() method in the legacy Mongo shell returns a string representation of the ObjectId MongoDB.

It is important to note that the legacy Mongo shell is still supported in MongoDB 5.0, but the newer Mongosh shell is recommended for new development and migration.

Important Operations Using MongoDB ObjectId

Creating MongoDB ObjectId

To create a new ObjectId() MongoDB use the following:

Syntax:

The above line of code will return a newly generated ObjectID.

In this example, the newly generated MongoDB ObjectId is:

creating a new objectid syntax

ObjectID Timestamp

This method extracts the timestamp from the ObjectId MongoDB and returns it as a Date object that can be formatted or manipulated as needed. As a result, there is no need to save the creation time of a document separately. The getTimestamp method can instead be used to retrieve the creation time. This not only saves space but also ensures that the creation time is always accurate and consistent with the MongoDB ObjectId.

Example 1:

Syntax:

We declare a variable named "newID" to store a newly created ObjectID MongoDB. Then we try to get the timestamp using the getTimestamp() method.

Therefore we get the output:

Thus we get the creation time of the document in ISO Date Format.

obtaining timestamp in iso date format syntax

Example 2:

In this example, we will find the timestamp using the MongoDB ObjectID of a document that has already been created.

Let us consider the ObjectID - "645a636cc7e8e9e46ec89d30" which we have created previously.

Syntax:

Therefore, we get the output:

This is the creation time of the document in ISO Date Format.!

getting data form a previously created document

ObjectID to String Conversion

Sometimes we may need the value of MongoDB ObjectId in a string format. This can be done using toString() in MongoDB.

Let us understand how this can be done with an example.

Example 1:

We generate a new ObjectId MongoDB and convert it into string format.

Syntax:

We get the following output:

Therefore we generate a new MongoDB ObjectId and toString() converts and returns the MongoDB ObjectId into string format.

converting the objectid in string format using toString method

Example 2:

In this example we will convert and return the string format of the ObjectID of a document that has already been created, using toString().

Let us consider the ObjectID - "645a636cc7e8e9e46ec89d30" which we have created previously.

Syntax:

We get the following output:

Therefore toString() converts and returns the already created ObjectId MongoDB into the string format.

toString converts and returns the already created MongoDB ObjectId into string format

Examples

Generating a New ObjectID

We can generate a new ObjectId MongoDB using MongoDB ObjectId(). This method does not have any argument inside it.

Syntax:

Therefore output will be:

Therefore the value of newObjId is: ObjectId("645b0fa4c7e8e9e46ec89d3b")

creating a new mongodb objectid syntax

Specifying a Hexadecimal String

We can use the ObjectId() method MongoDB to create a new MongoDB ObjectId with a distinct hexadecimal string.

Syntax:

Therefore the output would be:

Therefore the value of newObjId is: ObjectId("645b0fa4c7e8e9e46ec89a9b")

specifying a hexadecimal string syntax using objectid

Specifying an Integer String

We can generate a new MongoDB ObjectId using an integer.

Syntax:

The output will be:

Therefore the value of newObjId is: ObjectId("00000020c7e8e9e46ec89d3c")

specifying an integer string syntax using objectid

Accessing the Hexadecimal String

We can access the hexadecimal string we created using the str method.

Syntax:

This operation will return the following hexadecimal string

Returning a Hexadecimal String

We can use the toString() method to return the ObjectId MongoDB in hexadecimal string format.

Syntax:

The output will be:

returning a hexadecimal string using toString syntax

FAQs

Q. Is it possible to change the value of an ObjectId MongoDB?

A. No, we cannot change a MongoDB ObjectId's value. It is a one-of-a-kind identifier that therefore cannot be changed.

Q. How to compare two MongoDB ObjectIds?

A. Two MongoDB ObjectIds can be compared using the equals() method. It returns "true" if two ObjectIds match and "false" if they do not.

Q. Are ObjectId MongoDB values indexed in MongoDB?

A. ObjectId MongoDB values are automatically indexed in MongoDB which improves query performance.

Conclusion

  • MongoDB ObjectId is a twelve-byte BSON type unique identifier for MongoDB documents that acts as a primary key for MongoDB documents.
  • It consists of a four-byte timestamp, a random five-byte value generated once per process that is unique to the machine and process, and, a three-byte incrementing counter that is set to a random value.
  • ObjectId MongoDB accepts only one argument as input. It can accept a hexadecimal or an integer input. Format: ObjectId()
  • ObjectId.getTimestamp() returns the object’s timestamp as a Date.
  • ObjectId.toString() returns the string representation of the ObjectId.
  • ObjectId.valueOf() returns the “ObjectId” of the object itself.
  • The ObjectId.str returns the object’s hexadecimal string representation.
  • The legacy Mongo shell was replaced by a new shell called Mongosh with the release of MongoDB 5.0. The MongoDB ObjectId() methods in Mongosh behave slightly differently than in the legacy Mongo shell.
  • We can create a new ObjectId MongoDB, extract the timestamp from the MongoDB ObjectId and return it as a Date object, and convert the ObjectId MongoDB in string format using toString().
  • We can also use the MongoDB ObjectId() method to create a new ObjectId MongoDB with a distinct hexadecimal string or with an integer.