codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🍃

MongoDB

22 / 65 topics
19Indexing Basics20Creating Indexes21Compound Indexes22Unique Indexes23Geospatial Indexes24Explain Command
Tutorials/MongoDB/Unique Indexes
🍃MongoDB

Unique Indexes

Updated 2026-04-20
3 min read

Unique Indexes

Unique indexes ensure that the indexed fields contain unique values, preventing duplicate entries within a collection. This is crucial for maintaining data integrity and enforcing business rules. In this section, we will explore how to create, manage, and utilize unique indexes in MongoDB.

Understanding Unique Indexes

A unique index guarantees that each value in the specified field(s) is distinct across all documents in a collection. This is particularly useful for fields like email addresses or usernames where uniqueness is essential.

Key Characteristics of Unique Indexes

  • Prevent Duplicates: Ensures no two documents have the same value in the indexed field.
  • Performance Optimization: Improves query performance by reducing the number of potential matches.
  • Error Handling: If a duplicate key error occurs, MongoDB will prevent the operation and return an error.

Creating Unique Indexes

MongoDB provides several ways to create unique indexes. The most common methods are using the createIndex method or the ensureIndex method (deprecated).

Using createIndex

The createIndex method is the recommended way to create indexes in MongoDB.

db.collection.createIndex({ fieldName: 1 }, { unique: true });

Example: Creating a unique index on the email field.

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

Using ensureIndex (Deprecated)

While ensureIndex is deprecated, it can still be used for backward compatibility. However, it's recommended to transition to using createIndex.

db.collection.ensureIndex({ fieldName: 1 }, { unique: true });

Example: Creating a unique index on the username field.

db.users.ensureIndex({ username: 1 }, { unique: true });

Managing Unique Indexes

Once an index is created, you can manage it using various MongoDB commands.

Listing Indexes

To list all indexes on a collection, use the getIndexes method.

db.collection.getIndexes();

Example: Listing all indexes on the users collection.

db.users.getIndexes();

Dropping Unique Indexes

If you need to remove a unique index, use the dropIndex method.

db.collection.dropIndex(indexName);

Example: Dropping a unique index named email_1.

db.users.dropIndex("email_1");

Best Practices for Unique Indexes

  • Choose Appropriate Fields: Select fields that naturally enforce uniqueness, such as email addresses or usernames.
  • Avoid Overuse: While unique indexes are powerful, they can impact write performance. Use them judiciously.
  • Handle Errors Gracefully: Implement error handling to manage duplicate key errors gracefully in your application logic.
  • Monitor Performance: Regularly monitor the performance of your database and adjust indexes as needed.

Real-World Example

Consider a social media platform where users have unique usernames. To enforce this uniqueness, you can create a unique index on the username field.

db.users.createIndex({ username: 1 }, { unique: true });

If an attempt is made to insert a user with a duplicate username, MongoDB will return an error:

try {
    db.users.insertOne({ username: "john_doe" });
} catch (error) {
    console.error("Error inserting document:", error);
}

In this scenario, the application can handle the error by prompting the user to choose a different username.

Conclusion

Unique indexes are a powerful feature in MongoDB that help maintain data integrity and optimize query performance. By understanding how to create, manage, and utilize unique indexes effectively, you can build robust applications with efficient data handling capabilities. Always consider the trade-offs between uniqueness enforcement and write performance when designing your database schema.


PreviousCompound IndexesNext Geospatial Indexes

Recommended Gear

Compound IndexesGeospatial Indexes