The MongoDB E11000 Duplicate Key Error means a document was inserted or updated into a collection that already contained a document with the same value for a unique index. This prevents data corruption by enforcing uniqueness where it’s expected.

Here are the most common reasons this happens and how to fix them:

1. Accidental Duplicate Insert

This is the most frequent cause. You’re trying to insert a document, and a document with the same unique key already exists.

Diagnosis: Check the document you’re trying to insert. Specifically, look at the fields that are part of a unique index.

db.collection.find({ _id: "the_duplicate_id_value" })

or if the unique index is on another field, say email:

db.collection.find({ email: "the_duplicate_email_value" })

Then, examine the document you’re attempting to insert to see if it matches.

Fix: You have a few options:

  • Update the existing document: Instead of inserting, use $set to update the document with the duplicate key.
    db.collection.updateOne(
       { _id: "the_duplicate_id_value" },
       { $set: { new_field: "new_value" } }
    )
    
    This mechanically replaces the document with the matching key, ensuring uniqueness.
  • Insert a new document with a different key: If the key is supposed to be unique per record and you’re creating a new record, generate a new unique value for the indexed field before insertion. This ensures the new document has a distinct identifier.
  • Remove the duplicate: If the duplicate was an error and shouldn’t exist, delete it.
    db.collection.deleteOne({ _id: "the_duplicate_id_value" })
    
    This cleans up the erroneous entry, allowing your new insert to proceed.

Why it works: By either modifying the existing document, creating a new one with a unique identifier, or removing the erroneous duplicate, you eliminate the condition that violates the unique index constraint.

2. Application Logic Error (Race Condition)

Your application might be trying to create a record that it thinks doesn’t exist, but another concurrent operation created it just moments before.

Diagnosis: Enable MongoDB’s detailed logging. Look for E11000 errors occurring in rapid succession, potentially with different document data but the same unique key value. In your application logs, look for multiple attempts to insert the same logical entity.

Fix: Implement upsert logic in your application or use MongoDB’s findAndModify or findOneAndUpdate with the upsert: true option.

db.collection.findOneAndUpdate(
   { _id: "the_potential_duplicate_id" }, // The unique key
   { $set: { field1: "value1", field2: "value2" } }, // Fields to set/update
   { upsert: true, returnDocument: "after" } // Create if not found, return updated doc
)

Why it works: The upsert: true option tells MongoDB to insert the document if no document matches the query criteria (the unique key). If a document does match, it will update it instead of throwing an error. This single atomic operation prevents the race condition.

3. Incorrectly Configured Unique Index

You might have created a unique index on a field that you later decided should not be unique, or you might have added a unique constraint unintentionally.

Diagnosis: Inspect your collection’s indexes:

db.collection.getIndexes()

Look for an index marked as unique: true on the field causing the E11000 error.

Fix: Drop the unique index if it’s not actually required.

db.collection.dropIndex("index_name_or_specification")

For example, if the index is on the email field and its name is email_1:

db.collection.dropIndex("email_1")

Why it works: Removing the unique: true constraint from the index definition tells MongoDB to no longer enforce uniqueness for that field, allowing multiple documents to have the same value.

4. Case Sensitivity Differences

If your unique index is on a string field and your application is inserting data with different casing, MongoDB treats them as distinct by default. However, if you have a collation that makes the index case-insensitive, then this can be a cause.

Diagnosis: Check the index definition for a collation option, specifically locale and strength.

db.collection.getIndexes()

If you see a collation like { locale: "en", strength: 1 } or { locale: "en", strength: 2 }, it means the index is case-insensitive. Then check your insert data for variations in casing on the indexed field.

Fix:

  • Standardize casing in your application: Before inserting, convert the string to a consistent case (e.g., all lowercase).
    const normalizedString = originalString.toLowerCase();
    // Then insert with normalizedString
    
    This ensures that data intended to be the same is represented identically, satisfying the case-insensitive index.
  • Remove the case-insensitive collation: If you intended the index to be case-sensitive, drop and recreate the index without the collation.
    db.collection.dropIndex("index_name_with_collation")
    db.collection.createIndex({ field_name: 1 }, { unique: true, name: "new_index_name" })
    
    This reverts the index to its default case-sensitive behavior.

Why it works: By either normalizing the input data to match the index’s sensitivity or by adjusting the index’s sensitivity to match your data’s intended uniqueness, you resolve the conflict.

5. Compound Unique Index Issues

If you have a unique index spanning multiple fields (a compound unique index), the error occurs when the combination of values across those fields is duplicated, not necessarily a single field’s value.

Diagnosis: Identify all fields in the compound unique index using db.collection.getIndexes(). Then, check the documents you are trying to insert and compare the combination of values for these fields against existing documents.

db.collection.find({
  field1: "value1",
  field2: "value2"
})

Compare this to the document you’re trying to insert.

Fix:

  • Adjust the combination of values: Ensure the combination of values for the indexed fields in your new document is unique. This might involve changing one or more of the fields.
  • Remove the compound unique index: If the combination of fields doesn’t actually need to be unique, drop the index.
    db.collection.dropIndex("compound_index_name")
    
  • Split into separate indexes: If individual fields within the compound index need to be unique, create separate unique indexes for them instead.

Why it works: You are either ensuring that the unique combination of data points remains distinct or removing the constraint if it’s no longer necessary, thus resolving the E11000 error.

6. Data Migration or Bulk Load Errors

During a large data migration or bulk insert, a duplicate key can be introduced if the source data has duplicates, or if the process is interrupted and restarted incorrectly.

Diagnosis: This is often caught by the E11000 error itself. The key value reported in the error is your primary clue. You’ll need to trace that specific value back to the source data or the import script.

Fix:

  • Cleanse source data: Before loading, run a script on your source data to identify and remove or de-duplicate entries that would violate unique constraints.
  • Use ordered: false for bulk operations: When performing a bulk write (e.g., insertMany), setting ordered: false allows the operation to continue even if some documents fail due to duplicate keys. You can then inspect the results to identify and handle the duplicates.
    db.collection.insertMany([
       { _id: 1, name: "A" },
       { _id: 2, name: "B" },
       { _id: 1, name: "C" } // Duplicate _id
    ], { ordered: false })
    
    This will insert { _id: 1, name: "A" } and { _id: 2, name: "B" }, but the insert for { _id: 1, name: "C" } will fail, and the operation will continue.
  • Implement de-duplication logic: If you can’t clean the source, build logic into your import script to check for existing keys and update or skip as appropriate.

Why it works: Proactive data cleansing or using features that allow partial success and error reporting during bulk operations helps manage and resolve duplicate key issues introduced during large data movements.

The next error you’ll likely encounter after fixing E11000 is related to a different constraint or a more fundamental issue, such as insufficient disk space if you’re performing large data modifications, or a network timeout if your operations are taking too long due to complex queries or inefficient indexing.

Want structured learning?

Take the full Mongodb course →