Home › Databases

E11000 duplicate key error collection — how to fix

MongoServerError: E11000 duplicate key error collection: test.users index: email_1 dup key: { email: "ada@example.com" }
MongoServerError: E11000 duplicate key error collection: test.users index: username_1 dup key: { username: null }

Quick fix: Read the index: and dup key: parts. If the value really exists, update instead of insert (or use an upsert). If the dup key is null, documents are missing that field: drop the stale index with db.users.dropIndex("username_1") or recreate it with a partialFilterExpression.

What it means

The collection has a unique index (every collection has one on _id), and the write would produce a second document with the same indexed value. The error tells you exactly where:

List the indexes to see what is unique:

db.users.getIndexes()

Cause 1: the value really already exists

db.users.findOne({ email: "ada@example.com" })

If you meant "create or update", use an upsert:

db.users.updateOne(
  { email: "ada@example.com" },
  { $set: { name: "Ada" } },
  { upsert: true }
)

In application code, catch the error (err.code === 11000) and return a friendly "already registered" message instead of a 500. Two concurrent upserts on the same key can still race; retry once on 11000.

Cause 2: dup key: { field: null } - missing fields

A normal unique index treats a missing field as null, so only one document may lack it. The second document without username fails.

This often comes from a stale index: you once had a username field with unique: true, removed it from your schema, but the index is still in the database.

db.users.dropIndex("username_1")

If the field is optional but must be unique when present, use a partial index:

db.users.createIndex(
  { username: 1 },
  { unique: true, partialFilterExpression: { username: { $type: "string" } } }
)

Cause 3: duplicate _id

index: _id_ means you are inserting a document with an _id that already exists, often by reusing the same object in a loop (the driver adds _id to the object on the first insert):

for (const name of names) {
  await col.insertOne({ name });   // new object each time - fine
}

Don't insert the same JavaScript object twice, and don't copy _id when cloning documents.

Cause 4: Mongoose unique: true

In Mongoose, unique is not a validator; it only asks Mongoose to build a unique index. Consequences:

Find duplicates before creating the index:

db.users.aggregate([
  { $group: { _id: "$email", n: { $sum: 1 }, ids: { $push: "$_id" } } },
  { $match: { n: { $gt: 1 } } }
])

Cause 5: bulk inserts

insertMany stops at the first duplicate by default. To insert everything else and skip duplicates, pass { ordered: false } and handle the error that lists the failed documents.

Last updated 2026-12-01.