Explorer
MongoDB

ObjectId Structure

Structure of MongoDB ObjectId

By default, MongoDB assigns a 12-byte BSON ObjectId to the _id field of every newly inserted document. It is globally unique across distributed machines without requiring centralized sequence generators.

12-Byte Internal Anatomy

Byte Segment Size Hex Chars Contents & Generation Purpose
Timestamp 4 bytes 8 chars Unix epoch timestamp in seconds. Provides rough chronological ordering.
Process Random 5 bytes 10 chars Unique random value generated once per machine and process.
Incrementing Counter 3 bytes 6 chars Monotonically incrementing counter initialized to a random value.

Key Properties & Utilities

  • Timestamp Extraction: The creation time can be extracted directly without storing a separate createdAt field:
    CODE
    const timestamp = doc._id.getTimestamp();
  • Natural Sorting: Sorting by { _id: 1 } naturally sorts documents roughly by creation timestamp.
  • Hex Representation: Serialized as a 24-character hexadecimal string in JSON APIs (e.g. "507f1f77bcf86cd799439011").

Finished this lesson?

Mark this chapter complete to update your learning streak and unlock the next lesson.