10. Unique Indexes and Data Integrity
A unique index prevents multiple indexed entries from having the same key, subject to the index type and its null or missing-field behavior. It is useful for requirements such as unique usernames, email addresses, or external identifiers.
Before creating a unique index on existing data, check for duplicates. If duplicates violate the uniqueness rule, index creation will fail until the data is corrected or the rule is redesigned.
A unique index is a database-level integrity mechanism and is stronger than checking for duplicates only in application code. Application-side checks can race when two requests attempt to create the same value concurrently.
Think carefully about case sensitivity, normalization, missing values, and whether uniqueness should apply to all documents or only a subset.
A unique index cannot be created successfully if existing documents violate the uniqueness constraint.
db.users.createIndex({ usernameNormalized: 1 }, { unique: true });
// Before creating the index, inspect duplicate values.
db.users.aggregate([
{ $group: { _id: "$usernameNormalized", count: { $sum: 1 } } },
{ $match: { count: { $gt: 1 } } }
]);- Unique indexes enforce uniqueness at the database level.
- Check and resolve existing duplicates before creation.
- Normalize values if business uniqueness is case-insensitive.
- Understand how missing and null values interact with the chosen index.
Why is a unique index safer than only checking uniqueness in application code?