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.

CategoryIndex & Admin
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

db.<collection>.createIndex(<keys>, <options>)

⚙️ Parameters

index keyField-to-direction mapping, e.g. {age: 1, name: -1}.
optionsOptional. 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏