This error occurs when you try to create an index with a name that already exists but specifies different fields or options. MongoDB requires each index name to uniquely identify a specific index definition.
This error indicates that MongoDB cannot create an index because an index with the specified name already exists in the collection, but it has a different key specification (fields being indexed) or different index options. MongoDB uses index names to uniquely identify indexes within a collection. When you attempt to create an index, MongoDB checks if an index with that name already exists. If it does and the key specification or options differ from the existing index, MongoDB throws this error to prevent index conflicts. This commonly occurs during application upgrades, schema migrations, or when index definitions in your code don't match what's actually deployed in the database. It can also happen after MongoDB version upgrades that change automatic index naming conventions (e.g., from underscores to periods in field names).
Connect to your MongoDB instance and check what indexes currently exist on the collection:
// Using mongosh
db.yourCollection.getIndexes()Look for the index name mentioned in the error message. Note its current key specification and options. Compare this with what your application is trying to create.
Once you've identified the conflicting index, drop it using its name:
// Using mongosh
db.yourCollection.dropIndex("index_name")
// Or using Node.js driver
await collection.dropIndex("index_name");Warning: Dropping an index temporarily removes query optimization for queries using that index. Plan this during a maintenance window if the index is heavily used.
If you want to drop all indexes except _id (use with caution):
db.yourCollection.dropIndexes()After dropping the old index, create the new index with your desired key specification:
// Using mongosh
db.yourCollection.createIndex(
{ fieldName: 1, anotherField: -1 },
{ name: "custom_index_name" }
)
// Or using Node.js driver
await collection.createIndex(
{ fieldName: 1, anotherField: -1 },
{ name: "custom_index_name" }
);If you don't specify a name, MongoDB will auto-generate one based on the field names and sort order.
Alternatively, if you want to keep the old index and create a new one, simply use a different name:
// Create index with a unique, descriptive name
db.yourCollection.createIndex(
{ email: 1 },
{ name: "email_index_v2", unique: true }
)This approach is useful during gradual migrations where you want both indexes available temporarily.
Ensure your application's index creation code matches your database state:
// Mongoose example - ensure index definitions are consistent
const userSchema = new Schema({
email: { type: String, index: { unique: true, name: "email_unique_idx" } },
username: String
});
// Or explicitly define indexes
userSchema.index({ email: 1 }, { unique: true, name: "email_unique_idx" });Remove or update any old index definitions that reference the previous index name or specification.
Index Naming Conventions: MongoDB auto-generates index names using the pattern field1_direction_field2_direction (e.g., email_1_createdAt_-1). However, in MongoDB 4.2+, nested field naming changed from underscores to periods (e.g., profile_name_1 became profile.name_1), which can cause conflicts during upgrades.
Production Index Management: In production environments, use MongoDB's background index building to avoid blocking operations:
db.collection.createIndex({ field: 1 }, { background: true, name: "field_idx" })Note: The background option is deprecated in MongoDB 4.2+ as all indexes are built in the background by default.
Handling Multiple Environments: When managing indexes across dev, staging, and production, consider using migration tools like migrate-mongo or Prisma migrations to ensure consistent index state. Always include explicit index names in your definitions to avoid auto-naming conflicts.
Mongoose Auto-Index: If using Mongoose, be aware that autoIndex: true (default in development) can cause this error if your schema definitions don't match existing indexes. In production, set autoIndex: false and manage indexes through explicit migrations.
StaleShardVersion: shard version mismatch
How to fix "StaleShardVersion: shard version mismatch" in MongoDB
MongoOperationTimeoutError: Operation timed out
How to fix "MongoOperationTimeoutError: Operation timed out" in MongoDB
MongoServerError: PlanExecutor error during aggregation :: caused by :: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation.
How to fix "QueryExceededMemoryLimitNoDiskUseAllowed" in MongoDB
MissingSchemaError: Schema hasn't been registered for model
How to fix "MissingSchemaError: Schema hasn't been registered for model" in MongoDB/Mongoose
CastError: Cast to ObjectId failed for value "abc123" at path "_id"
How to fix "CastError: Cast to ObjectId failed" in MongoDB