If you omit _id on insert, MongoDB generates an ObjectId. Apps can use UUID strings or custom keys when needed.
Default _id
const r = db.items.insertOne({ name: 'Cable' })
r.insertedId
db.items.findOne({ _id: r.insertedId })Practice: Run in mongosh on your practice database.
Custom _id
db.items.insertOne({ _id: 'SKU-1001', name: 'Adapter' })Custom string IDs work when natural keys are stable—avoid hot shards on monotonic inserts at huge scale.
ObjectId in queries
const { ObjectId } = require('mongodb')
// In mongosh, insertedId is already ObjectId:
db.items.find({ _id: ObjectId('507f1f77bcf86cd799439011') })
Important interview questions and answers
- Q: ObjectId vs UUID?
A: UUIDs are opaque strings; ObjectIds are BSON-native and compact. - Q: Monotonic _id shard risk?
A: Rising ObjectIds on one shard can create hotspots—hash or distribute keys.
Self-check
- What happens if insert omits _id?
- When might you choose a string _id?
Tip: Custom string _ids are fine for natural keys; avoid hot monotonic shard keys at huge scale.
Interview prep
- Custom _id?
- Allowed when natural keys are stable.
- Hot shard risk?
- Monotonic rising keys can concentrate writes on one shard.