createIndex() (Create an Index)
Last updated: 2026-10-09
createIndex() (Create an Index)
createIndex() builds a single index to speed up queries, e.g. `db.users.createIndex({ age: 1 }, { unique: true })`. The value is 1 for ascending, -1 for descending; text, hashed, and 2dsphere index types are also supported. A unique index enforces field uniqueness. Note that building an index on a large collection can take a while and block writes — schedule it off-peak in production.
| Category | Index & Admin |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.createIndex(<keys>, <options>)
⚙️ Parameters
| index key | Field-to-direction mapping, e.g. {age: 1, name: -1}. |
|---|---|
| options | Optional. Options like unique, sparse, name, background. |
Returns:The name of the new index (string).
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// createIndex: ascending unique index on age
const idx = db.users.createIndex({ age: 1 }, { unique: true })
idx
Output:
'age_1'
📌 Notes
- Default index name is 'field_direction'; override with the name option
- A unique index rejects duplicates with DuplicateKeyError
- Compound index field order matters — the leftmost prefix applies
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QHow do I create a unique index with createIndex?
AAdd {unique: true} to the options, e.g. db.users.createIndex({email: 1}, {unique: true}).
QDoes createIndex block queries?
AOlder builds briefly impacted writes even in background mode; 4.2+ hybrid builds affect reads/writes far less, but still prefer off-peak timing for large collections.
QHow do I create a compound index?
APass multiple fields, e.g. db.users.createIndex({age: 1, name: -1}); queries using the leftmost prefix benefit.