Skip to content
MongoDB: E11000 duplicate key error collection

MongoDB: E11000 duplicate key error collection

DodaTech 2 min read

The MongoDB error “E11000 duplicate key error collection” occurs when an insert or update operation violates a unique index constraint on the collection.

What It Means

MongoDB enforces uniqueness on fields that have a unique index — most commonly the _id field, but also any field with { unique: true } defined. When you try to insert a document with a value that already exists in a unique index, MongoDB rejects the operation.

Why It Happens

  • You inserted a document with a duplicate _id value.
  • A unique index exists on a field (e.g., email, username) and the new document uses an existing value.
  • An upsert (updateOne with upsert: true) matched no document due to a wrong filter and tried to insert a new document that violates the index.
  • A bulk insert contains documents with duplicate key values among themselves.
  • A previous failed migration left partial data that conflicts with new inserts.

How to Fix It

1. Identify the duplicate key index

mongosh mydb
db.collection.getIndexes()

Look for indexes with unique: true.

2. Find the conflicting document

db.collection.find({ email: 'duplicate@example.com' })

3. Remove or update the duplicate

db.collection.deleteOne({ _id: ObjectId('...') })

4. Use upsert with a precise filter

db.collection.updateOne(
  { email: 'user@example.com' },
  { $set: { name: 'User', email: 'user@example.com' } },
  { upsert: true }
)

5. Drop the unique index (if appropriate)

db.collection.dropIndex('email_1')

FAQ

Can I ignore duplicate key errors during a bulk insert?
Yes. Use ordered: false in insertMany to continue inserting valid documents after a duplicate error. MongoDB will still fail on the duplicate but will process the remaining documents.
How do I create a compound unique index?
Use db.collection.createIndex({ field1: 1, field2: 1 }, { unique: true }). This enforces uniqueness on the combination of both field values, not each field individually.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro