68
MongoDBERRORCommonSystemHIGH confidence

Attempted to create an index that already exists with different options

What this means

This error occurs when you try to create an index with the same key pattern as an existing index, but with different options (e.g., name, uniqueness). MongoDB does not allow two indexes with the same key specification but different properties.

Why it happens
  1. 1Running a `createIndex` command for an index that already exists but with a new name
  2. 2Trying to change an existing index from non-unique to unique (or vice-versa)
  3. 3Attempting to change the collation or other options of an existing index by recreating it
How to reproduce

An index on `name` exists, and a new command tries to create another index on `name` with a different name.

trigger — this will error
trigger — this will error
db.users.createIndex({ name: 1 }, { name: "name_index_v1" });
// The following fails because an index on { name: 1 } already exists.
db.users.createIndex({ name: 1 }, { name: "name_index_v2" });

expected output

MongoServerError: Index already exists with a different name

Fix 1

Drop the Old Index First

WHEN You need to change the options of an existing index.

Drop the Old Index First
// Drop the existing index.
db.users.dropIndex("name_index_v1");

// Create the new index with the desired options.
db.users.createIndex({ name: 1 }, { name: "name_index_v2", unique: true });

Why this works

To modify an index's options, you must first drop the existing index and then create the new one with the updated configuration. This is an atomic process that requires downtime for the index.

Fix 2

Make `createIndex` Calls Idempotent

WHEN In deployment scripts where the index may or may not exist.

Make `createIndex` Calls Idempotent
// This command will succeed if the index already exists with the same options.
db.users.createIndex({ name: 1 }, { name: "name_index_v1" });

Why this works

If you call `createIndex` with the exact same key and options as an existing index, the command does nothing and succeeds. Ensure your deployment scripts are consistent to avoid this error.

What not to do

Ignore the error in a deployment script

This might mean that your database is not getting the intended index update (e.g., a change in collation or uniqueness). The script should handle this case explicitly, usually by dropping the old index first.

Sources
Official documentation ↗

mongodb/mongo src/mongo/base/error_codes.yml

db.collection.createIndex()

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All MongoDB errors