Quiz Entry - updated: 2026.07.05
What is a unique index in MongoDB and how do you create one?
A unique index forbids duplicate values for a field and speeds up lookups; create one with createIndex({ field: 1 }, { unique: true }).
await votes.createIndex(
{ 'email': 1 },
{ unique: true }
);
Benefits:
- Fast lookups - queries on indexed fields are faster
- No duplicates - inserting a duplicate value throws an error (code 11000)
Use unique indexes for fields like email addresses, usernames, or IDs.
Go deeper:
Unique Indexes (MongoDB Manual) — single-field vs compound unique indexes, the duplicate-key error, and the one-null-only rule.