How to Fix MongoDB Duplicate Key Error (E11000)
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: truein update operations that may insert new documents. - Use
ordered: falsein 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
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro