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).

CategoryBSON Types
MongoDB Version1.0+
Example Languagemongosh (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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏