Question 4 / 50
What is ObjectId, and when would you not use one as _id?
Short answer
ObjectId is the default unique _id: 12 bytes with a timestamp, randomness, and a counter, unique across clients without a central sequence. Use a natural key instead when the document already has a stable unique identifier you will look up by anyway — an email, an SKU, a UUID from another system.
Why?
_id is immutable and required. Inventing a random string as _id without a uniqueness story is worse than ObjectId. A natural _id avoids a second unique index, but only if the value never changes. Email as _id is a trap the first time someone renames their login.
Example
db.users.insertOne({
name: "Rahul",
email: "rahul@example.com"
})
// _id is assigned automatically as an ObjectIdInterview tip
Say _id is immutable. That one sentence prevents a class of 'can I update _id?' follow-ups.
Common mistake
Storing _id as a string in application code and then querying with that string against ObjectId fields.
How did you do?
Learn
Cheat Sheet