MongoDB Indexes, Explain Plans, and Performance/Enforce uniqueness with an index

Prevent duplicate values at write time.

Section: Create indexes

Enforce uniqueness with an index

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

Great for usernames, emails, external ids, and other unique keys.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Create indexes
Create a single-field index
Index one frequently filtered field.
OpenIn sheetjavascriptsame section
Create a compound index
Index fields used together in filters or sorts.
OpenIn sheetjavascriptsame section
Create a text index
Enable text search over string content.
OpenIn sheetjavascriptsame section
List indexes on a collection
Inspect existing indexes.
OpenIn sheetjavascriptsame section
Explain a query
Show the execution plan for a `find()` query.
OpenIn sheetjavascript1 tag match
Force a specific index with hint
Test how a query behaves with a chosen index.
OpenIn sheetjavascript1 tag match