What is a MongoDB ObjectId?
A MongoDB ObjectId is a unique identifier used as the primary key for documents in a MongoDB database. It ensures that each document can be uniquely identified. Here’s a breakdown of its structure:
Structure of an ObjectId:
- Timestamp (4 bytes):
- Represents the creation time of the ObjectId.
- Provides information about when the document was created.
- Machine Identifier (3 bytes):
- A unique identifier for the machine where the ObjectId was generated.
- Ensures uniqueness across different servers.
- Process Identifier (2 bytes):
- Identifies the process that generated the ObjectId.
- Ensures uniqueness across different processes running on the same machine.
- Counter (3 bytes):
- A counter, starting with a random value.
- Ensures uniqueness among ObjectIds generated within the same second on the same machine by the same process.
Key Features:
- Globally Unique: ObjectIds are unique across different machines and processes, preventing collisions.
- Sortable: Since ObjectIds contain a timestamp, they are roughly sorted in the order they were created.
- Compact: At 12 bytes, ObjectIds are compact and efficient for indexing.
Use Cases:
- Primary Keys: ObjectIds are often used as the default primary key (_id) for MongoDB documents.
- Timestamp Retrieval: The embedded timestamp can be used to retrieve the creation date of a document.
Using ObjectIds ensures that each document in your MongoDB collection is uniquely identifiable, supporting efficient database operations and queries.