0
0
MongoDBquery~5 mins

ObjectId and how it is generated in MongoDB

Choose your learning style9 modes available
Introduction

An ObjectId is a unique ID used to identify documents in MongoDB. It helps find and organize data easily.

When you want to uniquely identify each record in a MongoDB collection.
When you need a timestamp to know when a document was created.
When you want a small, fast, and unique ID without extra setup.
When you want to avoid manually creating IDs for your data.
When you want to sort documents by creation time automatically.
Syntax
MongoDB
ObjectId()
ObjectId is a 12-byte unique identifier generated automatically by MongoDB.
It contains a timestamp, machine ID, process ID, and a counter to ensure uniqueness.
Examples
Creates a new unique ObjectId with the current timestamp.
MongoDB
new ObjectId()
Creates an ObjectId from a given 24-character hex string.
MongoDB
ObjectId("507f1f77bcf86cd799439011")
Sample Program

This inserts a document with name 'Alice' and then retrieves its ObjectId.

MongoDB
db.test.insertOne({name: "Alice"})
var doc = db.test.findOne({name: "Alice"})
doc._id
OutputSuccess
Important Notes

The first 4 bytes of ObjectId represent the creation timestamp in seconds.

ObjectId is unique across machines and processes, so no two documents get the same ID.

You can extract the creation time from an ObjectId using its timestamp.

Summary

ObjectId is a unique 12-byte ID automatically created by MongoDB.

It includes a timestamp, so you know when the document was made.

Use ObjectId to identify and sort documents easily without extra work.