What is the _id field in MongoDB and how are ObjectIds generated?
Understand MongoDB's _id primary key and how 12-byte ObjectIds are generated from a timestamp, random value, and counter, plus when to use a custom _id.
Expected Interview Answer
The _id field is the mandatory primary key that uniquely identifies every document in a MongoDB collection, and if you do not supply one, the driver automatically generates a 12-byte ObjectId.
Every document must have a unique _id, and MongoDB indexes it automatically. By default _id is an ObjectId: 12 bytes made of a 4-byte Unix timestamp (seconds), a 5-byte random value unique to the machine/process, and a 3-byte incrementing counter. This structure makes ObjectIds globally unique without coordination and roughly monotonic, so they sort close to insertion order. You may also assign your own _id value of any type as long as it is unique.
- Guarantees a unique identity for every document
- Auto-generated with no central coordination needed
- Encodes a creation timestamp you can extract
- Roughly time-ordered for efficient range scans and inserts
- Automatically indexed for fast lookups
AI Mentor Explanation
An ObjectId is like a ball's unique code stitched from the over's clock time, the ground and bowler it came from, and a running delivery number. No two grounds coordinate yet every ball's code is unique, and because the clock leads the code, sorting the codes replays the innings almost in the exact order the balls were bowled.
Step-by-Step Explanation
Step 1
Know _id is mandatory
Every document must have an _id; it is the primary key and is unique within the collection.
Step 2
Let the driver generate it
If you omit _id on insert, the client driver creates a 12-byte ObjectId before sending the document.
Step 3
Understand the byte layout
4 bytes timestamp (seconds), 5 bytes random per process, 3 bytes incrementing counter — 12 bytes total, shown as 24 hex characters.
Step 4
Extract the timestamp
Call getTimestamp() on an ObjectId to read the creation time embedded in its first four bytes.
Step 5
Use a custom _id when needed
Assign your own _id (string, number, UUID) when you have a natural key, ensuring it stays unique.
What Interviewer Expects
- Knowing _id is the required, auto-indexed primary key
- The 12-byte ObjectId structure: timestamp, random, counter
- That ObjectIds are generated client-side by the driver
- That _id can be any unique type, not only ObjectId
- Awareness that ObjectIds are roughly, not strictly, monotonic
Common Mistakes
- Saying ObjectIds are generated by the server, not the driver
- Claiming _id must always be an ObjectId
- Believing ObjectIds are strictly sequential and globally ordered
- Thinking the timestamp has millisecond precision (it is seconds)
- Forgetting that _id is automatically indexed and immutable
Best Answer (HR Friendly)
“The _id is a unique label that every MongoDB record must carry, like a serial number. If you do not provide one, MongoDB automatically creates an ObjectId that packs in the time it was made plus values that keep it unique, so records get a built-in identity and rough time order for free.”
Code Example
// No _id supplied -> driver generates an ObjectId
const res = await db.collection('users').insertOne({ name: 'Ada' });
console.log(res.insertedId); // e.g. ObjectId('66a1f3b2c4d5e6f7a8b9c0d1')
console.log(res.insertedId.getTimestamp()); // creation time from the first 4 bytes
// Supplying a custom _id (must be unique)
await db.collection('users').insertOne({ _id: '[email protected]', name: 'Ada' });Follow-up Questions
- What are the 12 bytes of an ObjectId and what does each part do?
- Can you use your own value for _id instead of an ObjectId?
- Are ObjectIds strictly monotonic across a cluster?
- How do you extract the creation time from an ObjectId?
- Why might a UUID be preferred over an ObjectId as _id?
MCQ Practice
1. How many bytes is a MongoDB ObjectId?
An ObjectId is 12 bytes (represented as 24 hexadecimal characters): 4-byte timestamp, 5-byte random, 3-byte counter.
2. Where is the ObjectId typically generated?
By default the client driver generates the ObjectId before sending the insert, so no server round-trip is needed for the id.
3. Which statement about the _id field is true?
_id is mandatory, must be unique, is automatically indexed, and can be any type as long as it stays unique.
Flash Cards
What is the _id field? — The mandatory, unique, automatically indexed primary key of every MongoDB document.
What are the 12 bytes of an ObjectId? — 4-byte Unix timestamp (seconds) + 5-byte random per process + 3-byte incrementing counter.
Who generates the ObjectId? — The client driver, before the document is sent to the server, if no _id is provided.
Can _id be something other than an ObjectId? — Yes — any unique value (string, number, UUID) can be used as _id.
How do you get an ObjectId's creation time? — Call getTimestamp() to read the timestamp encoded in its first four bytes.