What is the _id field and what is an ObjectId?
BeginnerConceptMongoDB
Answer
Short answer
Every MongoDB document must have a unique _id field — it's the primary key, automatically indexed. If you don't provide one, MongoDB generates an ObjectId: a 12-byte value made of a timestamp, a random value and a counter, so it's unique without coordination between servers.
Example
db.orders.insertOne({ item: "laptop" })
// { acknowledged: true, insertedId: ObjectId("6650f1c2a7b3e4d5f6a7b8c9") }
ObjectId("6650f1c2a7b3e4d5f6a7b8c9").getTimestamp()
// ISODate("2026-05-24T...") ← creation time is built in
Custom _id
db.users.insertOne({ _id: "[email protected]", name: "Asha" }) // any unique value works
Notes
_idcan't be changed after insert.- Because ObjectIds increase with time, sorting by
_idroughly sorts by creation time.
What to say in the interview
"_id is the mandatory, unique, indexed primary key. By default it's an ObjectId combining a timestamp, random bytes and a counter, so it's generated client-side without collisions and even encodes creation time."
More on MongoDB
What is MongoDB and how is it different from MySQL or PostgreSQL?BeginnerHow do you run MongoDB, log in and work with data?BeginnerWhat is a NoSQL database?BeginnerWhat is a document and a collection in MongoDB?BeginnerWhat is BSON?BeginnerHow do you connect to MongoDB and explore databases and collections?Beginner