createIndexes() (Create Multiple Indexes)
Last updated: 2026-10-09
createIndexes() (Create Multiple Indexes)
createIndexes() creates several indexes in one call, e.g. `db.users.createIndexes([{ key: { age: 1 } }, { key: { email: 1 }, unique: true }])`. Compared to looping createIndex(), it batches index builds into a single request — more efficient for initial setup and migrations. Each definition needs key and may carry options. Note that the _id index always exists and cannot be dropped.
| Category | Index & Admin |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.createIndexes([<indexSpecs>, ...])
⚙️ Parameters
| index definitions array | Each element has a key plus optional flags, e.g. {key: {age: 1}, unique: true}. |
|---|
Returns:List of names of the created indexes.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// createIndexes: age index plus unique email index in one call
const names = db.users.createIndexes([
{ key: { age: 1 } },
{ key: { email: 1 }, unique: true }
])
names
Output:
[ 'age_1', 'email_1' ]
📌 Notes
- Saves round trips versus calling createIndex() repeatedly
- Identical indexes already present are skipped and reused
- Building still costs resources on large datasets
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QcreateIndexes or createIndex — which is better?
AUse createIndexes() to build several indexes in one request; createIndex() reads cleaner for a single one.
QCan createIndexes mix plain and unique indexes?
AYes — give each spec its own options, e.g. {key: {age: 1}} and {key: {email: 1}, unique: true}.
QWhat happens when I create a duplicate index?
AAn identical index is skipped and its existing name returned — no error.