πŸ”§ Error Fixes
Β· 1 min read

MongoDB: E11000 Duplicate Key Error β€” How to Fix It


E11000 duplicate key error collection: mydb.users index: email_1 dup key

You’re inserting a document with a duplicate value in a unique index.

Why this happens

MongoDB enforces unique indexes at the storage level. When you create a unique index on a field (like email), any attempt to insert or update a document with a value that already exists in that field will fail with E11000. This also applies to the default _id field, which always has a unique index.

Fix 1: Use updateOne with upsert

await db.collection('users').updateOne(
  { email: 'alice@example.com' },
  { $set: { name: 'Alice' } },
  { upsert: true }
);

Fix 2: Check before inserting

const existing = await db.collection('users').findOne({ email });
if (!existing) {
  await db.collection('users').insertOne({ email, name });
}

Fix 3: Handle the error

try {
  await db.collection('users').insertOne(doc);
} catch (err) {
  if (err.code === 11000) {
    console.log('Duplicate email');
  }
}

Alternative solutions

Use bulkWrite with ordered: false to continue inserting valid documents even when some fail:

await db.collection('users').bulkWrite(
  docs.map(doc => ({ insertOne: { document: doc } })),
  { ordered: false }
);

Drop and recreate the index if it was created by mistake on a field that shouldn’t be unique:

await db.collection('users').dropIndex('email_1');

Prevention

  • Use upsert: true by default for idempotent operations (like syncing data from external sources).
  • Review your indexes with db.collection.getIndexes() to ensure unique constraints match your data model.

Related: PostgreSQL: Connection Refused fix Β· MySQL: Lock Wait Timeout fix