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
_idvalue. - A unique index exists on a field (e.g.,
email,username) and the new document uses an existing value. - An upsert (
updateOnewithupsert: 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro