ObjectId (Object Identifier)
Last updated: 2026-10-09
ObjectId (Object Identifier)
ObjectId is MongoDB's default _id type — a 12-byte unique identifier: 4-byte timestamp + 5-byte random + 3-byte counter. It is auto-generated when a document is inserted without _id, is unique across distributed systems, and embeds the creation time (extractable).
| Category | BSON Types |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
// Auto-generated
{ _id: ObjectId("64c8a1b2f3d4e5a6b7c8d9e0") }
// Get timestamp
ObjectId("...").getTimestamp()
Returns:Returns an ObjectId instance; prints as a 24-hex-char string
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// ObjectId: inspect after insert
const oid = ObjectId()
print(oid.getTimestamp()) // creation time
Output:
2026-09-25T08:30:00Z
📌 Notes
- 12 bytes = 4-byte Unix timestamp + 5-byte random + 3-byte counter
- ObjectIds are roughly monotonic; sorting by _id approximates insertion order
- String form is 24 hex chars
- getTimestamp() extracts the creation time
🏷️ Related Tags
💡 Related Cases
Documents and BSON: The Cornerstone of MongoDB Data
Inserting Documents: A Detailed Explanation of `insertOne` and `insertMany`
Mongoose Advanced Patterns: Performance and Flexibility
Mongoose Models and Schema Design
Mongoose Data Validation and Middleware
📚 Related Tutorials
❓ FAQ
QCan I use an auto-increment integer for _id?
AYes — specify _id manually at insert. But auto-increment integers need coordination under distributed writes; ObjectId exists precisely to avoid that.
QWhat format is an ObjectId string?
A24 hex characters, e.g. 64c8a1b2f3d4e5a6b7c8d9e0 — one byte per pair.
QCan ObjectIds be sorted by time?
AApproximately — the first 4 bytes are a timestamp, so sorting by _id roughly follows insertion order, not exact time.