database
constraint_error
ai_generated
true
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: mydb.mycollection index: _id_ dup key: { _id: ObjectId('...') }
ID: database/mongodb-duplicate-key
92%Fix Rate
94%Confidence
65Evidence
2023-06-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7 | active | — | — | — |
Root Cause
An insert or update attempted to create a duplicate value for a field with a unique index (including _id). Common with manual _id assignment, unique index on business fields, or retry logic inserting the same document twice.
genericWorkarounds
-
93% success Use updateOne with upsert:true to handle duplicates as updates
Replace insertOne with: db.collection.updateOne({ uniqueField: value }, { $set: { ...document } }, { upsert: true }). This inserts if the document does not exist or updates if it does. -
90% success Let MongoDB generate _id automatically instead of assigning manually
Remove the _id field from your insert documents. MongoDB will auto-generate unique ObjectId values. If you need a business key, use a separate unique index and handle E11000 with retry/upsert logic.
Dead Ends
Common approaches that don't work:
-
Dropping the unique index on _id to prevent duplicate key errors
95% fail
The _id index is mandatory in MongoDB and cannot be dropped. Even for other unique indexes, dropping them removes data integrity guarantees and leads to duplicate documents.
-
Using unordered bulk writes without error handling to push through duplicates
75% fail
Unordered writes continue past errors but silently skip duplicate documents. Without checking the BulkWriteResult for errors, you lose data and have no record of which documents failed.
Error Chain
Preceded by:
Frequently confused with: