What is ObjectId Type in MongoDB: Explanation and Usage
ObjectId is a special 12-byte unique identifier used as the default value for the _id field in documents. It ensures each document has a unique ID that encodes creation time and other information.How It Works
Think of ObjectId as a unique name tag for each document in a MongoDB collection. It is made up of 12 bytes that include the time the document was created, a machine identifier, a process ID, and a counter. This combination makes sure that no two documents get the same ID, even if they are created at the same time on different machines.
This is like giving each document a special code that tells you when and where it was made, so you can always find it quickly and avoid mix-ups. The ObjectId is generated automatically if you don’t provide an _id when inserting a document.
Example
This example shows how to create a document with an ObjectId in MongoDB using the MongoDB shell.
const doc = { name: "Alice" }; db.users.insertOne(doc); printjson(doc._id);
When to Use
Use ObjectId whenever you need a unique identifier for documents in MongoDB. It is perfect for most cases because it is fast to generate and guarantees uniqueness without extra work.
For example, when storing user profiles, orders, or blog posts, ObjectId helps you quickly find and manage each item. You can also extract the creation time from the ObjectId if you want to know when a document was added.
Key Points
- Unique: Each
ObjectIdis unique across machines and time. - Automatic: MongoDB creates it automatically if you don’t specify an
_id. - Contains timestamp: You can get the creation time from the
ObjectId. - 12 bytes: Compact size storing multiple pieces of info.