ObjectId in MongoDB (original) (raw)

Last Updated : 5 May, 2026

The _id field uniquely identifies each MongoDB document, using ObjectId by default to ensure uniqueness and efficient data management.

ObjectId Structure

The ObjectId is composed of 12 bytes, broken down as follows:

objectid_structure

The ObjectId is represented as a hexadecimal string, and its default format is:

ObjectId()

ObjectId is a 12-byte unique identifier represented as a 24-character hexadecimal string, automatically generated by MongoDB but can be custom-defined if unique.

db.collection.insertOne({ _id: ObjectId("64f1a2b3c4d5e6f789012345") })

Example of ObjectId in MongoDB

When we insert a document into a collection, MongoDB automatically assigns a unique_id using the ObjectId format.

Screenshot-2026-02-10-125059

Methods of MongoDB ObjectId

MongoDB provides several useful methods to interact with the ObjectId. These methods allow you to access the timestamp, convert the ObjectId to a string, and more.

1. Creating an ObjectId

We can generate a new ObjectId using the ObjectId() constructor.

newObjectId = ObjectId()

**Output:

Screenshot-2026-02-10-125151

2. Getting the Timestamp from ObjectId

We can retrieve the creation timestamp of the ObjectId using the getTimestamp() method. This method returns the timestamp as a Date object.

var id =new ObjectId();     
id.getTimestamp()

**Output:

Screenshot-2026-02-10-125342

3. Converting ObjectId to String

We can convert an ObjectId into its string format using the str property.

 new ObjectId().toString()

**Output:

Screenshot-2026-02-10-125540

4. Getting the Hexadecimal Representation

You can also use the valueOf() method to get the hexadecimal representation of the ObjectId.

new ObjectId().valueOf()

**Output:

Screenshot-2026-02-10-125633

Using ObjectId for Querying

Since ObjectId is used as the default unique identifier for MongoDB documents, we can use it to efficiently query for documents by their _id.

db.student_gfg.findOne({ _id: ObjectId("5f92cbf10cf217478ba93561") })

In this query, the ObjectId is used to retrieve a document with a specific _id. Since ObjectId is indexed, these queries are very efficient.

Usage of ObjectId Vs Custom _id