0
0
MongodbConceptBeginner · 3 min read

What is ObjectId Type in MongoDB: Explanation and Usage

In MongoDB, 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.

javascript
const doc = { name: "Alice" };
db.users.insertOne(doc);
printjson(doc._id);
Output
ObjectId("64b7f8e2f1a4c3d2e5a6b7c8")
🎯

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 ObjectId is 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.

Key Takeaways

ObjectId is MongoDB’s default unique identifier for documents.
It encodes creation time, machine ID, process ID, and a counter.
MongoDB generates ObjectId automatically if no _id is provided.
You can extract the document creation time from the ObjectId.
Use ObjectId for fast, unique, and compact document IDs.