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.

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

📝 Syntax

db.<collection>.createIndexes([<indexSpecs>, ...])

⚙️ Parameters

index definitions arrayEach 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

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.
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%

🙏 帮我们做得更好

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

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