Mongodb Primary Key: Example to set _id field with ObjectId()

⚡ Smart Summary

MongoDB Primary Key is the _id field that uniquely identifies every document in a collection. By default it holds an automatically generated ObjectId, but you can also assign your own value to the _id field when inserting a document.

  • 🔑 Primary Key Role: The _id field is the primary key that uniquely identifies each document in a MongoDB collection.
  • 🆔 Default ObjectId: If you omit _id, MongoDB automatically adds a unique 12-byte ObjectId value to the document.
  • ⏱️ Time-Ordered: An ObjectId begins with a 4-byte timestamp, so IDs are roughly sortable by creation time.
  • ✍️ Custom Keys: You can supply your own _id value, such as a number or string, when inserting a document.
  • 🔒 Immutable: Once set, the _id value cannot be changed; you must delete and re-insert to alter it.

What is Primary Key in MongoDB?

In MongoDB, _id field as the primary key for the collection so that each document can be uniquely identified in the collection. The _id field contains a unique ObjectID value.

By default when inserting documents in the collection, if you don’t add a field name with the _id in the field name, then MongoDB will automatically add an Object id field as shown below

Primary Key in MongoDB

When you query the documents in a collection, you can see the ObjectId for each document in the collection.

If you want to ensure that MongoDB does not create the _id Field when the collection is created and if you want to specify your own id as the _id of the collection, then you need to explicitly define this while creating the collection.

When explicitly creating an id field, it needs to be created with _id in its name.

Let’s look at an example on how we can achieve this.

db.Employee.insert({_id:10, "EmployeeName" : "Smith"})

Code Explanation:

  1. We are assuming that we are creating the first document in the collection and hence in the above statement while creating the collection, we explicitly define the field _id and define a value for it.

If the command is executed successfully and now use the find command to display the documents in the collection, the following Output will be shown

Output:

Primary Key in MongoDB

The output clearly shows that the _id field we defined while creating the collection is now used as the primary key for the collection.

What is ObjectId in MongoDB?

An ObjectId is the default value type that MongoDB assigns to the _id primary key. It is a 12-byte identifier that is designed to be globally unique across servers and collections, so two documents almost never receive the same value. Because the client driver can generate an ObjectId without asking the server, MongoDB can insert documents quickly and scale across many machines without a central counter.

Each ObjectId is stored in a compact binary form but is displayed as a 24-character hexadecimal string, for example ObjectId(“507f1f77bcf86cd799439011”). The first bytes are based on the current time, which means the values increase steadily as documents are created. This makes ObjectId not only unique but also roughly sortable by insertion order, a useful property when you want the newest or oldest records first.

Structure of a MongoDB ObjectId

A MongoDB ObjectId is exactly 12 bytes long, and each part has a specific meaning. Understanding the structure helps explain why ObjectIds are unique and time-ordered:

  • 4-byte timestamp: The number of seconds since the Unix epoch, recording when the ObjectId was created. This makes IDs sortable by time.
  • 5-byte random value: A value generated once per process, combining the machine and process identity, so different clients produce different IDs.
  • 3-byte incrementing counter: A counter that starts from a random value and increases with each new ObjectId in the same second, preventing collisions during rapid inserts.

Together, these three parts guarantee that every ObjectId is unique, even when many documents are inserted at the same moment across different servers. You can read the embedded creation time at any point by calling the getTimestamp() method on an ObjectId.

Advantages of Using ObjectId as a Primary Key

Using the default ObjectId as the _id primary key offers several practical benefits, which is why most MongoDB collections rely on it:

  • Automatic generation: You do not need to create or manage key values yourself, reducing the chance of duplicate keys.
  • Global uniqueness: ObjectIds stay unique across servers, so they work well in distributed and sharded deployments.
  • Built-in timestamp: The embedded creation time lets you sort or filter documents by age without an extra date field.
  • High performance: Client-side generation avoids a round trip to the server, keeping inserts fast.

While ObjectId suits most applications, you can still choose a custom _id, such as an email address or product code, when a natural business key makes queries simpler. The right choice depends on how you plan to look up and relate your data.

FAQs

No. The _id field is immutable once a document is created. To change it, you must delete the existing document and insert a new one with the desired _id value.

The _id field accepts most BSON types, including ObjectId, integers, strings, and even embedded documents. The only rule is that the value must be unique within the collection and cannot be an array.

Yes. MongoDB creates a unique index on the _id field for every collection automatically. This index cannot be dropped and makes lookups by primary key very fast.

AI can explain an ObjectId’s timestamp, generate code to extract creation time with getTimestamp(), and convert ObjectIds to strings, helping developers debug and understand document identifiers more quickly.

Yes. AI can advise whether to keep the default ObjectId or use a custom _id such as an email or UUID, based on your query patterns, uniqueness needs, and sharding plans.

Summarize this post with: