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.
| Category | Admin Commands |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (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
| key | Index keys and directions, e.g. { userId: 1, createdAt: -1 } |
|---|---|
| unique | Set true for a unique index |
| name | Index 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
- Compound field order determines which queries and sorts an index serves
- Unique indexes reject duplicates with duplicate key errors
- Indexes cost disk and memory — don't index every field
🏷️ Related Tags
💡 Related Cases
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.