0
0
MongodbConceptBeginner · 3 min read

Unique Index in MongoDB: Definition and Usage

A unique index in MongoDB is a special type of index that ensures all values in the indexed field are unique across the collection. It prevents duplicate entries for that field, helping maintain data integrity.
⚙️

How It Works

Think of a unique index like a guest list for a party where each guest must have a unique name. MongoDB uses this index to check every new entry and makes sure no two entries have the same value in the indexed field.

When you add a unique index to a field, MongoDB automatically rejects any insert or update operation that tries to create a duplicate value in that field. This helps keep your data clean and consistent without duplicates.

💻

Example

This example shows how to create a unique index on the email field in a MongoDB collection called users. It prevents two users from having the same email address.

mongodb
db.users.createIndex({ email: 1 }, { unique: true })

// Trying to insert duplicate emails will cause an error

// Insert a user
 db.users.insertOne({ name: "Alice", email: "alice@example.com" })

// Insert another user with the same email (will fail)
 db.users.insertOne({ name: "Bob", email: "alice@example.com" })
Output
{ acknowledged: true, insertedId: ObjectId("...") } // Error on second insert: // E11000 duplicate key error collection: test.users index: email_1 dup key: { email: "alice@example.com" }
🎯

When to Use

Use a unique index when you want to make sure no two documents in a collection have the same value for a specific field. This is common for fields like email addresses, usernames, or product codes.

It helps avoid mistakes like duplicate user accounts or repeated product entries, which can cause confusion or errors in your application.

Key Points

  • A unique index enforces uniqueness for the indexed field.
  • It prevents duplicate values during insert or update operations.
  • Useful for fields that must be unique like emails or IDs.
  • Creating a unique index on existing data with duplicates will fail.

Key Takeaways

A unique index ensures no duplicate values exist in the indexed field.
It automatically blocks inserts or updates that would create duplicates.
Use unique indexes for fields like emails, usernames, or IDs to keep data consistent.
Creating a unique index requires existing data to be free of duplicates.
Unique indexes improve data integrity and prevent common data errors.