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

  • _id can't be changed after insert.
  • Because ObjectIds increase with time, sorting by _id roughly 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."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MongoDB basics

More on MongoDB