dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Home/Error Library/mongodb-e11000-duplicate-key-error
MongoDB
MongoDB 6.0 - 8.0Writes & Indexes
3 min read
E11000 duplicate key error collection: prod.users index: email_1 dup key: { email: "a@b.com" }

MongoDB Unique Key Collision: Concurrency Races, Upsert Race Conditions & Idempotent Write Patterns

Diagnosing E11000 errors caused by concurrent insert races, index verification, and implementing atomic upsert with $setOnInsert.

Reviewed by:Senior Database Architect & SRE (dataiotech Labs)
Tested Versions: MongoDB 6.0 / 7.0 / 8.0

Operational Verification & Reliability Metadata

Last Technical Review: 2 Kasım 2026
Tested VersionsMongoDB 7.0.8, 8.0.1 (Docker / Atlas / Ubuntu 24.04)
Required PrivilegesreadWrite role on database
Risk Assessment
MediuminsertMany with ordered:true halts the entire batch upon encountering first E11000 error
Expected OutputgetIndexes confirming unique constraint and atomic upsert completing successfully
Rollback Procedure:Remove duplicate document or rebuild index
MongoDB Docs: Unique Indexes & E11000 Error
First 60 Seconds Emergency Protocol:

The error string is a symptom, not the root cause. Do not restart the server blindly. Run the diagnostic queries below to pinpoint the actual failure mode.

▸Symptom

Document insertions fail with unique index violation:

plaintext
MongoServerError: E11000 duplicate key error collection: prod.users index: email_1 dup key: { email: "a@b.com" }

▸What You See in Production

Parallel registration requests or concurrent worker threads collide during write operations.


▸Root Cause Matrix

ProbabilityRoot CauseDescription
%65Concurrent Race ConditionsTwo threads check existence with findOne, then both attempt insertOne.
%25Batch Insert Default (`ordered: true`)A single duplicate halts entire insertMany batch execution.
%10Null Value Key CollisionsMultiple missing fields indexed as duplicate null values.

▸EMERGENCY RUNBOOK (0-5 min)

javascript
// 1. Inspect existing duplicate record db.users.find({ email: "a@b.com" }); // 2. Implement atomic upsert db.users.updateOne( { email: "a@b.com" }, { $set: { last_login: new Date() }, $setOnInsert: { created_at: new Date(), name: "Ali" } }, { upsert: true } ); // 3. Unordered batch insertions db.users.insertMany(docs, { ordered: false });

▸PERMANENT BLUEPRINT

  1. 1Atomic Upsert Logic: Replace read-then-write chains with atomic upserts.
  2. 2Sparse Indexes: Prevent null collisions with sparse or partial filter expressions.

▸Verification

javascript
db.users.getIndexes().filter(idx => idx.unique);

Other Database Error Triage Playbooks

Other battle-tested diagnostic guides for high-severity database errors.

All Errors (82)