Working with ObjectId and _id
Working
with ObjectId and _id in MongoDB
Introduction
As soon as you begin coding with MongoDB, one of the first
things you'll find in each document is the enigmatic appearing field named _id.
It's not merely an arbitrary string – it is an identifier and, as default, is
generated using a special type named ObjectId. Whether you're new to MongoDB or
you're looking to move beneath the surface, learning how _id and ObjectId work
is something that will make you a more effective user of MongoDB.
Explanation
What is _id?
In MongoDB, each document has to have an _id field. Imagine _id as a primary
key – it makes the document unique, so MongoDB can figure out how to retrieve,
update, or remove the correct one.
What is ObjectId?
ObjectId is a 12-byte id that MongoDB automatically creates if you don't supply
a custom _id. It will look something like this:
ObjectId("64ffbae5314a2187253fc5c1")
Each component of this ID has significance:
4 bytes: timestamp
3 bytes: machine ID
2 bytes: process ID
3 bytes: counter (preventing duplication)
This structure creates ObjectIds:
Globally unique
Time-sortable (on creation time)
Procedure
Here's how you work with _id and ObjectId in MongoDB:
1. Displaying _id in a document
When you insert a document with no _id, MongoDB automatically adds it.
db.users.insertOne({ name: "Alice" })
{
"_id": ObjectId("64ffbae5314a2187253fc5c1"),
"name": "Alice"
}
2. Using a custom _id
You can specify your own _id if you prefer:
db.users.insertOne({ _id: "user123", name:
"Bob" })
Every _id has to be distinct.
3. Querying with ObjectId
You have to use ObjectId() in order to query it properly.
db.users.find({ _id:
ObjectId("64ffbae5314a2187253fc5c1") })
4. Creating ObjectId manually
You can create one programmatically:
const id = new ObjectId();
Or even pull out its timestamp:
id.getTimestamp(); // returns ISODate
Future
Scope
- Sharding: MongoDB employs _id to split documents into shards.
- Time-based queries: With a timestamp in ObjectId, you can query documents by creation time.
- Optimized indexing: MongoDB utilizes _id as an index by default – excellent for performance.
- Custom ID generation: In systems of a large scale, developers can even create their own UUIDs or hash-based _ids for security or scaling purposes.
The _id field and ObjectId are not merely random IDs – they guarantee uniqueness, enable time tracking, and are deeply linked to MongoDB's performance and scaling mechanisms. Whether you have MongoDB generate them or generate your own, knowing how they work helps you develop better, more solid applications.
Vedansh Shah
University: Shree Balaji University, Pune
School: School of Computer Studies
Course: BCA (Bachelor of Computer Applications)
📸 Instagram 🔗 LinkedIn 🌐 Official Website
Excellent work
ReplyDeleteGood 👍 Job
ReplyDeleteExcellent 👍
ReplyDeleteNice 👍
ReplyDeleteIt's very nice
ReplyDeleteHelpful and good explanation
Great post! Really liked how you explained the difference between ObjectId and _id—super clear and easy to follow. It’s such a common point of confusion, and this definitely helped me understand it better. Keep sharing more stuff like this!
ReplyDeleteGreat Work..
ReplyDeleteGreat
ReplyDeleteExcellent Work 👍
ReplyDelete