Loading lessons...
The _id Field and ObjectId
The _id Field and ObjectId
Every document in a collection must have a unique _id field - it acts as the document's primary key. If you don't provide one, MongoDB generates an ObjectId for you.
Auto-generated _id
db.posts.insertOne({ title: "Hello" })
// result: { acknowledged: true, insertedId: ObjectId("507f1f77bcf86cd799439011") }
If your document has no _id, MongoDB adds one with a unique ObjectId. If you supply your own _id, it must be unique in the collection:
db.posts.insertOne({ _id: 10, title: "Inception" })
What's inside an ObjectId?
An ObjectId is 12 bytes:
- 4-byte timestamp - seconds since the Unix epoch (creation time)
- 5-byte random value - unique per machine and process
- 3-byte incrementing counter - a per-process counter
Reading the creation time
Because the first 4 bytes are a timestamp, you can recover when a document was created:
ObjectId("507f1f77bcf86cd799439011").getTimestamp()
Good to know
- ObjectIds are unique and sortable roughly by creation time.
- The
_idindex is automatically created and unique - you can't drop it. - In a projection,
_idis included unless you explicitly exclude it.
TL;DR
- Every document needs a unique
_id(primary key). - If missing, MongoDB generates an ObjectId.
- ObjectId = 4-byte timestamp + 5-byte random + 3-byte counter.