Course contentsShow
← System Design
Lesson 391 of 1,91911. NoSQL: Document StoresFree lesson

Primary Key and ObjectId Generation

How MongoDB automatically generates unique _id fields using ObjectIds that embed timestamp and machine information.

Primary Key and ObjectId Generation

What you'll learn: How MongoDB automatically creates unique document identifiers using ObjectIds that contain built-in timestamp and system information.

The _id Field in MongoDB

Every MongoDB document must have a unique identifier stored in the _id field—this is the primary key. If you don't provide one when inserting a document, MongoDB automatically generates an ObjectId for you.

What Is an ObjectId?

An ObjectId is a 12-byte identifier that MongoDB creates automatically. Think of it like a highly sophisticated serial number that tells you not just what the document is, but when and where it was created.

The 12 bytes break down like this:

  • 4 bytes: timestamp (seconds since Unix epoch)
  • 5 bytes: random value unique to the machine and process
  • 3 bytes: incrementing counter

This design ensures ObjectIds are globally unique across your entire distributed system without requiring coordination between servers.

Why This Matters

Analogy: Imagine concert tickets that embed the date, venue, and a unique sequence number all in one barcode. You can tell when and where each ticket was issued just by looking at it—no central database lookup needed.

Because the timestamp is embedded, documents are roughly sorted by creation time automatically. The random portion means two MongoDB servers can generate ObjectIds simultaneously without collisions. The counter handles multiple documents created in the same second on the same machine.

You can extract the creation timestamp from any ObjectId, making it useful for debugging and analytics without storing a separate createdAt field.

Key Takeaway: MongoDB's ObjectIds are self-contained unique identifiers that embed timestamp and machine information, enabling distributed document creation without central coordination.