0
0
MongoDBquery~3 mins

Why Custom _id values in MongoDB? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could name your data exactly how you want and never lose track of it again?

The Scenario

Imagine you have a big box of files, each with a random label. You want to find a specific file quickly, but the labels don't follow any order or pattern.

Every time you add a new file, you just stick a random number on it and hope it's unique.

The Problem

Manually creating unique labels is slow and confusing. You might accidentally reuse a label, causing mix-ups.

Searching for files becomes a guessing game, and organizing them is a headache.

The Solution

Using custom _id values in MongoDB lets you assign meaningful, unique labels to your data.

This way, you control how each item is identified, making it easier to find, update, or organize your data.

Before vs After
Before
db.collection.insertOne({name: 'Alice'})
After
db.collection.insertOne({_id: 'user_123', name: 'Alice'})
What It Enables

It enables you to create clear, predictable, and easy-to-use identifiers that fit your needs perfectly.

Real Life Example

In an online store, you can use product codes as _id values so you can quickly find or update products by their known codes instead of random numbers.

Key Takeaways

Manual IDs are random and hard to manage.

Custom _id values give you control and clarity.

This makes data easier to find, update, and organize.