MongoDB — E11000 duplicate key error on insert
Resolve MongoDB E11000 by identifying the unique index and using upsert or idempotent writes.
Symptoms
- E11000 duplicate key error collection: db.users index: email_1 dup key
- The error appears only under concurrency
- A retry after a transient failure inserts a duplicate
- The index name in the error is not one you created
Possible causes
- A unique index exists on the field being inserted with a duplicate value
- A retry replays an insert that partially succeeded
- A non-unique write assumed the field was unique
- A unique index was created but existing duplicates remain
Diagnosis steps
Read the index name and duplicate value
mongo --eval "db.users.getIndexes()"Interpretation
The index name in the error maps to a specific unique index, and the value shows which field collided.
Check for the existing document
mongo --eval "db.users.find({ email: '[email protected]' }).count()"Interpretation
If a document already exists, the insert is a genuine duplicate or a retry of a completed write.
Use upsert for idempotent writes
db.users.updateOne({ email }, { $setOnInsert: doc }, { upsert: true })Interpretation
Upsert avoids duplicate key errors by inserting only when absent.
Root cause
An insert or update violated a unique index because a document with the same indexed key already existed, or the operation is a retry of one that already succeeded.
Fix
Detect the duplicate and decide whether to update instead of insert, use upsert for idempotent writes, and make retry logic aware that a previous attempt may have committed.
Verify the fix
Rerun the write and confirm no duplicate key error, and confirm exactly one document exists for the key.
Symptom walkthrough
An insert fails with E11000 duplicate key error, naming the unique index and the duplicated value. This means a document with the same indexed key already exists, so the insert is either a genuine duplicate or a retry of a write that already succeeded. Under concurrency, two writers can race and one loses, which is expected behavior for a unique index rather than a defect in the database.
Fix in practice
Decide per case: use upsert when the write should be idempotent, catch the duplicate error and update when a record already exists, and make retry logic treat a duplicate as a possible sign of prior success. Removing a unique index should only happen if uniqueness is genuinely not required.
Verification
Rerun the write and confirm it succeeds without the duplicate error, then confirm exactly one document exists for that key. A single document confirms the idempotent handling works.
Diagnostic commands
Check the behavior with commands like these:
mongo --eval "db.users.getIndexes()"
mongo --eval "db.users.find({ email: '[email protected]' }).count()"
db.users.updateOne({ email }, { $setOnInsert: doc }, { upsert: true })