createIndexes (Build Indexes)

Last updated: 2026-10-09

createIndexes (Build Indexes)

createIndexes builds indexes on a collection — single-field, compound, unique, TTL, text, and geospatial. In mongosh the helper db.collection.createIndex({ field: 1 }) is typical. Index builds consume resources; on large collections reads and writes continue during the hybrid build (default since 4.2). Field order in compound indexes shapes query support.

CategoryAdmin Commands
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

db.orders.createIndex({ userId: 1, createdAt: -1 })
db.users.createIndex({ email: 1 }, { unique: true })
db.runCommand({ createIndexes: "orders", indexes: [{ key: { userId: 1 }, name: "user" }] })

⚙️ Parameters

keyIndex keys and directions, e.g. { userId: 1, createdAt: -1 }
uniqueSet true for a unique index
nameIndex name; auto-generated when omitted

Returns:Returns numIndexesBefore, numIndexesAfter, and ok

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// createIndexes: compound and unique indexes
use shop
db.orders.createIndex({ userId: 1, createdAt: -1 })
db.users.createIndex({ email: 1 }, { unique: true })

Output:

{ numIndexesBefore: 1, numIndexesAfter: 2, ok: 1 }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QHow should I order fields in a compound index?
APut equality-filter fields first, range and sort fields after.
QWhat happens on duplicate inserts with a unique index?
AThe insert fails with a duplicate key error.
QDoes index creation lock the database?
ASince 4.2 the hybrid build keeps reads and writes running, though CPU and I/O are consumed.
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%

🙏 帮我们做得更好

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

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