Skip to content

MongoDB Duplicate Key Error

Error message

                E11000 duplicate key error
              

Quick summary

You attempted to insert a document with a value that violates a unique index in MongoDB — the value already exists.

Why this happens

  • Inserting a document with an _id that already exists

  • Inserting a duplicate value in a field with a unique index

  • A race condition where two inserts happen simultaneously

  • Not checking for existing documents before inserting

Minimal example

✗ Broken code
db.users.insertOne({ _id: 1, name: 'Ada' });
// A document with _id: 1 already exists → E11000
✓ Fixed code
db.users.updateOne(
  { _id: 1 },
  { $set: { name: 'Ada' } },
  { upsert: true }
);

Using upsert with updateOne either updates the existing document or inserts a new one, avoiding the duplicate key error.

How to diagnose

  • Read the error to identify which index was violated and the duplicate key value

  • Query for the existing document: db.collection.findOne({ field: value })

  • Check your unique indexes: db.collection.getIndexes()

How to fix

  • Use a different value that does not already exist

  • Use upsert: db.collection.updateOne(filter, update, { upsert: true })

  • Check for an existing document before inserting

  • Remove the unique index if duplicates should be allowed

How to prevent

  • Check for existing documents before inserting

  • Use upsert patterns to avoid duplicate key errors

  • Handle E11000 errors gracefully in your application

Related Resources

Related Glossary

Related Lessons

← Back to language