Build indexes online
Create or change indexes while the collection keeps taking writes.
Create or change indexes while the collection keeps taking reads and writes, with no maintenance window.
Requirements
- A user with
dbAdminorreadWriteon the database.
Create the index
JavaScript
db.orders.createIndex({ customer: 1, created: -1 });createIndexes builds the index without stopping the collection's writes, which keep coming in during the build.
Change an existing index
JavaScript
db.runCommand({ collMod: "orders", index: { name: "customer_1_created_-1", hidden: true } });Hiding an index before dropping it lets you see whether any query misses it.
Check
Once the build finishes, db.orders.getIndexes() lists the new index next to the ones the collection already had.
Common problems
- The build fails if a document does not meet the index, for example a repeated value in a unique one; the error names the first one in
_idorder.