MongoDB "E11000 duplicate key error": What It Means and How to Fix It
MongoDB E11000 duplicate key error means a write broke a unique index. How to read it, fix null and stale-index cases, find duplicates and handle code 11000.
MongoDB's E11000 error means an insert or update would have put a value into a unique index that another document already has. The message names the collection, the index and the value that clashed. Often it's a real duplicate, like an email that's already registered. Just as often it's a surprise: several documents missing the same field, an old index left behind after a schema change, or two requests inserting the same thing at the same moment.
Checked against the MongoDB manual (unique and partial indexes, upsert behaviour, error codes), the MongoDB server source and the Mongoose FAQ and API docs in November 2026.
Here is the error as the Node.js driver or Mongoose prints it:
MongoServerError: E11000 duplicate key error collection: shop.users index: email_1 dup key: { email: "ana@example.com" }
In Python (PyMongo) it arrives as pymongo.errors.DuplicateKeyError with the same text. The numeric code is 11000, which MongoDB's error code list names DuplicateKey.
How to read the message
The server builds the message from three parts:
| Part | Example | Meaning |
|---|---|---|
collection: |
shop.users |
Database shop, collection users |
index: |
email_1 |
The unique index that refused the write. email_1 is the default name for an ascending index on email |
dup key: |
{ email: "ana@example.com" } |
The value that already exists |
The index name is the most useful part. If it's _id_, you're reusing a document ID. If it's an index you don't recognise, it's probably left over from an older version of your schema. If the value is null, the cause is missing fields, not a real duplicate.
Cause 1: a genuine duplicate
A user signs up with an email that's already registered, or an import runs twice. The unique index is doing its job.
Don't fix this by checking first ("find a user with this email, and insert if there isn't one"). Two requests can both check, both see nothing, and both insert. The index is what actually guarantees uniqueness, so let the insert fail and handle the error (see the last section). Normalise values before saving, too: Ana@Example.com and ana@example.com are different strings, so trim and lowercase emails in your code (Mongoose has a lowercase: true schema option for this).
Cause 2: dup key: { field: null }
E11000 duplicate key error collection: shop.users index: username_1 dup key: { username: null }
This catches most people out. The unique index docs explain that a document without the indexed field is stored in the index as null, so "a single-field unique index can only contain one document that contains a null value in its index entry." The first user without a username saves fine. The second fails.
If the field is genuinely optional, make the index partial, so uniqueness only applies to documents that have a real value:
db.users.createIndex(
{ username: 1 },
{ unique: true, partialFilterExpression: { username: { $type: "string" } } }
)
The partial index docs say that with a filter, "the unique constraint only applies to documents that meet the filter expression." $type: "string" excludes both missing fields and fields explicitly set to null (which some libraries write when a default is null). { $exists: true } is also allowed, but it would still index explicit null values. The docs recommend partial indexes over the older sparse: true option because they give you more precise control.
You can't edit an index's options in place. Drop the old one and create the new one, ideally when writes are quiet, because for a moment there is no uniqueness check:
db.users.dropIndex("username_1")
db.users.createIndex(/* as above */)
Cause 3: an old index you forgot about
You renamed username to handle, or removed unique: true from a field, but the index is still in the database. MongoDB keeps indexes until someone drops them. Now every new document lacks username, so they all collide on null in an index your code no longer mentions.
List what's really there:
db.users.getIndexes()
Drop anything stale with db.users.dropIndex("username_1"). In Mongoose, Model.diffIndexes() shows which indexes syncIndexes() would drop and create, and Model.syncIndexes() then makes the database match your schema. The Mongoose API docs warn that it "will drop any indexes that are not defined in the model's schema except the _id index", so run diffIndexes() first and check the list.
Cause 4: a duplicate _id
index: _id_ means you inserted a document whose _id already exists. MongoDB creates a unique index on _id for every collection. Common ways to get there:
- Hard-coding or copying an
_idfrom another document or a seed file. - Re-inserting the same JavaScript object. The Node.js driver adds an
_idto the object you pass toinsertOne, so inserting that object again, for example in a loop or a retry, reuses the ID. - Retrying a bulk insert that partly succeeded. The documents that went in the first time now collide.
Use updateOne with upsert: true when you mean "insert or update", or create fresh objects for each insert.
Cause 5: Mongoose unique: true didn't work, then suddenly did
The Mongoose FAQ is blunt about this: unique: true is not a validator. It's a shortcut for asking MongoDB to build a unique index. Until that index exists, duplicates save happily. If duplicates already exist when Mongoose tries to build it, the build fails and you get no uniqueness at all.
That leads to a common pattern: duplicates pile up in development, then someone builds the index (or it finally builds on a clean database) and E11000 appears. The FAQ recommends creating production indexes deliberately, noting that "mongoose is not an index management solution." Use await Model.init() in tests if you need to wait for indexes to finish building.
Finding the duplicates
Before you can create a unique index on existing data, you have to remove the duplicates. MongoDB "cannot create a unique index on the specified index field(s) if the collection already contains data that would violate the unique constraint." This aggregation lists every value that appears more than once, with the IDs involved:
db.users.aggregate([
{ $group: { _id: "$email", count: { $sum: 1 }, ids: { $push: "$_id" } } },
{ $match: { count: { $gt: 1 } } },
{ $sort: { count: -1 } }
], { allowDiskUse: true })
Decide which document to keep for each value (usually the oldest, or the one with the most data), merge anything you need from the others, and only then delete. Back up the collection with mongodump before a bulk delete; there's no undo.
Cause 6: upserts racing each other
updateOne(filter, update, { upsert: true }) looks safe, but two upserts that run at the same time can both find nothing and both insert. The update docs say that without a unique index, each one "may result in an insert, creating multiple documents." With a unique index on the filter fields, only one insert wins. The server then retries the others as updates only if all of these hold: the filter is a single equality (or an AND of equalities) on exactly the unique index's fields, the operation isn't an update-many, and the update doesn't modify those fields. Otherwise the losers get E11000. Keep the unique index, and in your code treat code 11000 from an upsert as "someone else just created it": retry once and it will find the document.
Handling code 11000 in your app
Catch the error by its code, not by matching text, and turn it into a useful response. The error carries keyPattern and keyValue fields, so you can tell the user which field clashed:
try {
await User.create({ email, name });
} catch (err) {
if (err.code === 11000) {
const field = Object.keys(err.keyValue ?? {})[0] ?? "value";
return res.status(409).json({ error: `That ${field} is already in use.` });
}
throw err;
}
A 409 Conflict tells the client the request was valid but clashes with existing data. Avoid echoing the duplicate value back for sensitive fields. For retried requests from clients (a double-clicked button, a network retry), unique keys pair well with Idempotency Keys: Making POST Requests Safe to Retry.
If you're coming from SQL, this is the same idea as Postgres's unique constraint error; "duplicate key value violates unique constraint": Causes and Fixes covers that side.
EasySpawn can provision MongoDB on the same server where Claude Code works, so the agent can run getIndexes() and the aggregation above against your real data instead of guessing from the schema file. It is pre-launch; join the waitlist.
Related: What Is MongoDB? A Beginner's Guide to Document Databases · "duplicate key value violates unique constraint": Causes and Fixes · Database Indexes: Why Your App Got Slow and How to Fix It · Idempotency Keys: Making POST Requests Safe to Retry
Keep reading
psql "connection to server on socket ... failed: No such file or directory": How to Fix It
psql connection to server on socket failed means no Postgres socket file was where psql looked. Fixes for a stopped server, wrong path, Docker and Homebrew.
What Is UTF-8? Character Encoding and Garbled Text (Mojibake) Explained
UTF-8 is the character encoding that lets computers store every language and emoji as bytes — and it's the default almost everywhere now. How encoding works, why you see garbled text like ’ or é, and how to fix it in HTML, databases, CSV files and code.