Skip to content

How to Fix MongoDB Duplicate Key Error (E11000)

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix MongoDB Duplicate Key Error (E11000). We cover key concepts, practical examples, and best practices.

The Problem

You insert a document and MongoDB returns:

MongoServerError: E11000 duplicate key error collection: mydb.users index: email_1 dup key: { email: "user@example.com" }

A unique index on the collection rejects the insert because another document already has the same value.

Quick Fix

1. Use upsert instead of insert

Replace insertOne with updateOne using the upsert option:

// Wrong — throws duplicate key error
await db.collection('users').insertOne({
  email: 'user@example.com',
  name: 'User'
})

// Right — insert or update
await db.collection('users').updateOne(
  { email: 'user@example.com' },
  { $set: { name: 'User', lastLogin: new Date() } },
  { upsert: true }
)

2. Use bulkWrite with ordered: false

For batch inserts where some documents may be duplicates:

// Wrong — whole batch fails on first duplicate
await db.collection('users').insertMany(documents)

// Right — skip duplicates, continue with rest
await db.collection('users').bulkWrite(
  documents.map(doc => ({
    insertOne: { document: doc }
  })),
  { ordered: false }
)

3. Find and remove duplicates

Find documents with duplicate keys:

const duplicates = await db.collection('users').aggregate([
  { $group: { _id: '$email', count: { $sum: 1 }, ids: { $push: '$_id' } } },
  { $match: { count: { $gt: 1 } } }
]).toArray()

Remove duplicates, keeping the oldest:

for (const doc of duplicates) {
  const [keep, ...remove] = doc.ids
  await db.collection('users').deleteMany({ _id: { $in: remove } })
}

4. Drop the unique index (if not needed)

If the unique constraint is unintentional:

// List indexes
db.collection('users').getIndexes()

// Drop the unique index (replace with actual index name)
db.collection('users').dropIndex('email_1')

5. Use a sparse or partial unique index

If the field is optional, use a sparse index to allow multiple documents without the field:

db.collection('users').createIndex(
  { email: 1 },
  { unique: true, sparse: true }
)

Prevention

  • Use upsert: true in update operations that may insert new documents.
  • Use ordered: false in bulk operations when duplicates are expected.
  • Validate input data at the application level before writing to MongoDB.
  • Use sparse unique indexes for optional fields.

Common Mistakes with duplicate key

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world MONGODB code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between a unique index and a primary key in MongoDB?

MongoDB automatically creates a unique index on the _id field (primary key). Additional unique indexes can be created on any field or combination of fields.

Why does a unique index throw E11000 when I insert a document?

The document you are inserting has a value for the indexed field that already exists in another document. The unique index enforces that no two documents share the same value.

Can I have a compound unique index?

Yes. db.collection('users').createIndex({ tenantId: 1, email: 1 }, { unique: true }) ensures the combination of tenantId and email is unique, while allowing the same email under different tenants.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro