Need Assistance?

support@tutorialshub.in

Databases, Collections & Documents

Understanding _id and ObjectId

ADVERTISEMENT
MongoDB Free Lesson
5 min read
ADVERTISEMENT

Every document in a MongoDB collection must have a unique _id field. If you omit _id when inserting, MongoDB automatically generates a 12-byte ObjectId containing:

  • 4 bytes: Unix timestamp (when the document was created)
  • 5 bytes: Random machine/process value
  • 3 bytes: Incrementing counter

Because the timestamp is embedded inside ObjectId, you can even extract the creation time using .getTimestamp()!

ADVERTISEMENT
Hi, I'm Tuby! Here to help you