Error
Error Code:
68
MongoDB Error 68: Duplicate Index Creation
Description
MongoDB Error 68, 'Index Already Exists', occurs when an operation attempts to create an index on a collection that already has an index with the same definition. This typically happens during script re-runs, schema migrations, or when an application's expected database state differs from the actual state.
Error Message
Index Already Exists
Known Causes
3 known causesRepeated Index Creation Command
An application or script attempts to execute an index creation command for an index that has already been successfully established on the collection.
Non-Idempotent Migration Scripts
Database migration scripts lack checks for existing indexes, leading to errors if they are re-run on a database that has already applied the index creation.
Database State Mismatch
The application's logic assumes a particular index does not exist, while the database environment has already had that index created, often due to manual intervention or out-of-sync environments.
Solutions
3 solutions available1. Verify and Skip Duplicate Index Creation easy
Check if the index already exists before attempting to create it, preventing the error.
1
Connect to your MongoDB instance using the `mongosh` shell.
mongosh
2
Switch to the database where the index creation is failing.
use your_database_name
3
List existing indexes for the collection to identify if the index already exists.
db.collection_name.getIndexes()
4
If the index already exists, remove the `createIndex` command from your script or application code that is causing the duplicate creation. If you are using an ORM or ODM, consult its documentation on how to manage schema migrations or index definitions.
// Example of index creation to remove if it already exists:
// db.collection_name.createIndex({ field1: 1, field2: -1 })
2. Drop and Recreate the Index easy
Remove the existing index and then create it again, useful for correcting incorrect index definitions.
1
Connect to your MongoDB instance using the `mongosh` shell.
mongosh
2
Switch to the database containing the collection with the duplicate index.
use your_database_name
3
Identify the name of the index that is causing the error by running `db.collection_name.getIndexes()`.
db.collection_name.getIndexes()
4
Drop the existing index using its name. Replace `'index_name'` with the actual name of the index you identified.
db.collection_name.dropIndex('index_name')
5
Now, recreate the index with the correct definition. Ensure the field(s) and order match your requirements.
db.collection_name.createIndex({ field1: 1, field2: -1 })
3. Handle Index Creation Gracefully in Application Code medium
Implement logic in your application to check for index existence before creating it.
1
In your application's database initialization or migration scripts, before calling `createIndex`, query for the existence of the index.
// Example in JavaScript using the official MongoDB driver:
async function ensureIndex(db, collectionName, indexDefinition) {
const indexes = await db.collection(collectionName).listIndexes().toArray();
const indexExists = indexes.some(index => {
// Compare index keys to the definition (simplified comparison)
return JSON.stringify(index.key) === JSON.stringify(indexDefinition);
});
if (!indexExists) {
console.log(`Creating index: ${JSON.stringify(indexDefinition)}`);
await db.collection(collectionName).createIndex(indexDefinition);
} else {
console.log(`Index already exists: ${JSON.stringify(indexDefinition)}`);
}
}
// Usage:
// const db = client.db('your_database_name');
// await ensureIndex(db, 'collection_name', { field1: 1, field2: -1 });
2
Alternatively, many MongoDB drivers and ODMs (like Mongoose for Node.js) provide options or methods to automatically handle index creation, often by checking for existence or using upsert-like behavior for schema definitions. Consult your specific driver/ODM documentation.
// Mongoose example:
const schema = new mongoose.Schema({
field1: String,
field2: Number
});
schema.index({ field1: 1, field2: -1 }); // Mongoose handles creation/updates