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

Also available as: JSON · Markdown
92%Fix Rate
94%Confidence
65Evidence
2023-06-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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.

generic

Workarounds

  1. 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.
  2. 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:

  1. 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.

  2. 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

Leads to:
Preceded by:
Frequently confused with: