What is ObjectId in MongoDB?

Beginner

Answer

ObjectId is a 12-byte unique identifier used as the default value for the _id field.

Structure (24 hex characters):

  • 4 bytes: Unix timestamp
  • 5 bytes: Random unique value
  • 3 bytes: Incrementing counter

Properties:

  • Automatically generated if not provided
  • Contains creation timestamp
  • Globally unique across machines
  • Sortable by creation time
// ObjectId example
ObjectId("507f1f77bcf86cd799439011")

// Extract timestamp
ObjectId("507f1f77bcf86cd799439011").getTimestamp()
// Returns: ISODate("2012-10-17T20:46:47Z")