Australian cloud for business software — built and run in Sydney since 2002

NetLeverage
NetLeverage

MongoDB "E11000 duplicate key error collection": find the clashing value, then change the data or the index

Technical article
Troubleshooting

About this article: This article is reviewed against the cited sources. This is source research, not lab validation. Check the stated versions and your own requirements before making changes.

When MongoDB answers E11000 duplicate key error collection: appdb.users index: email_1 dup key: { email: "pat@example.com" }, a unique index already holds that key, and the insert, update or index build you ran would store it a second time. The message names the collection, the index and the clashing key. Find the document that owns the key, then change the incoming data, remove the true duplicate, or narrow the index so it covers only the documents it should.

What the error means

In mongodb/mongo tag r8.0.4 the server builds the text from the collection, the index name and the key: it writes "E11000 duplicate key error", then collection:, the namespace, index:, the index name, dup key: and the key document. The error code behind it is 11000, named DuplicateKey in the same tag's error code list. The error also carries keyPattern and keyValue fields. Our own reading: the server sends both fields with the error, so a driver can read them. On an index with a collation, the same source also writes collation: into the message, and string values in keyValue are hex-encoded.

MongoDB's unique index page says that a unique index "ensures that the indexed fields do not store duplicate values", and that "By default, MongoDB creates a unique index on the _id field during the creation of a collection". So an _id clash and an email_1 clash are the same error from two different unique indexes.

Three behaviours from the same page matter here:

  • A unique compound index compares the combination of its fields, so the key shown lists every field of the index.
  • A document with a null or missing value in a unique single-field index is stored with a null key. The page says such an index "can only contain one document that contains a null value in its index entry".
  • With partialFilterExpression plus unique, the page says the unique constraint "only applies to documents that meet the filter expression".

For insertMany, the 8.0 page says ordered defaults to true and that if an insert fails with ordered set to true, "the server does not continue inserting records". With ordered: false the server continues and reports each failure.

Likely causes

Cause What you see How to confirm
The value already exists index: email_1, a real value in dup key findOne on that value returns a document
An _id is reused, for example a seed script run twice index: _id_ findOne({ _id: ... }) returns a document
A second document lacks a field that has a unique index dup key shows a null value (our reading of the null-key behaviour) find with $exists: false on that field returns one document already
Two documents in one bulk insert share a key The bulk error lists, in op, a document that shares its key with an earlier document of the same call The input list holds the key twice
A unique index build over data that already clashes The error comes from createIndex, not from a write An aggregation grouped on the key returns counts above 1

Prove the cause before changing anything

All of these commands only read.

  1. Take the namespace, the index name and the key from the message.

  2. List the indexes and find the one with that name:

db.users.getIndexes()

The page says the method returns documents that describe each index on the collection. Check that the index named in the message is the unique one and note its key pattern. If you did not name the index, MongoDB's createIndex page says it generates the name "by concatenating the names of the indexed fields and the sort order", which is why { email: 1 } becomes email_1.

  1. Find the document that already owns the key:
db.users.findOne({ email: "pat@example.com" })

findOne returns one document that satisfies the query. For an _id clash, query on _id instead. If the owner is the same record you are trying to insert, the application is writing it twice; if it is a different person, the data genuinely clashes.

  1. When an index build failed, count the clashes in the existing data. This assembles the $group and $match stages shown on MongoDB's pages (our own composition):
db.users.aggregate([
  { $group: { _id: "$email", n: { $sum: 1 }, ids: { $push: "$_id" } } },
  { $match: { n: { $gt: 1 } } }
])

Every row returned is a value that occurs more than once, and its ids lists the documents that share it (the $group page lists $push as returning "an array of expression values for documents in each group"). No row means the clash comes from the incoming write, not from stored data.

Fix

Choose by what step 3 found.

The incoming data is the problem

Where the owner is a different record, the application is supplying a value that must be unique and is not. Correct the source of the value, or have the code look the record up first. For an upsert, MongoDB's updateOne page says: "To avoid multiple upserts, ensure that the filter field(s) are uniquely indexed." For bulk loads, run with ordered: false and read the per-document errors, so one clash does not stop the batch. The rows that did not clash are stored and stay in the collection, so the load is partial until you correct the rejected rows and send them again. These are changes to application code and load scripts, not to the database, so no save-first step applies.

Two stored documents hold the same key

This case arises when the unique index could not be built, because the data already holds the same key twice. Which document to keep is a business decision; the database cannot make it. Once you have chosen the document to remove, take its _id from the ids list of step 4.

First save the current state, a dump of exactly that one document (add --uri and credentials as your deployment needs):

mongodump --db=appdb --collection=users --query='{ "_id": 1042 }' --out=users-before-1042

MongoDB's mongodump page says --query limits the output and requires --collection; it also says to enclose the query in single quotes.

Before you go on, check that the dump holds the document. The mongodump page says a directory dump has a subdirectory for each database and a BSON file for each collection, so the folder users-before-1042/appdb/ must contain users.bson. Do not delete anything if that file is missing.

Risk: the next command deletes one document, the user with _id 1042, from appdb.users. Anything that refers to that user stops finding it. The dump saved above holds that one document and nothing else.

Delete it by _id:

use appdb
db.users.deleteOne({ _id: 1042 })

The deleteOne page says the method "Removes a single document from a collection".

Only if you need to back out: restore the saved document, which writes it back into appdb.users and fails with the same error if a newer document now holds that key. The mongorestore page shows --nsInclude restoring one namespace from a dump directory.

Risk: the next command writes the saved document back into appdb.users. It fails with the same error if a newer document now holds that key. Do not add --drop, which the page says drops the collection before it restores.

mongorestore --nsInclude=appdb.users users-before-1042

Then run db.users.findOne({ _id: 1042 }) and check that it returns the document.

Many documents lack the field, so a unique index is too strict

If the clash is on a missing field and several documents may legitimately lack it, a partial unique index covers only documents that have the field. MongoDB's createIndex page documents the partialFilterExpression and name options; the partial indexes page documents the $exists filter.

First save the current state:

mongosh --quiet --eval 'use appdb' --eval 'db.users.getIndexes()' mongodb://localhost/ > users-indexes-before.txt

Disruptive step: the next two commands drop the unique index email_1 and build a partial unique index with the same name. Until the new index exists, nothing enforces uniqueness on email, so a duplicate email can be written in that window. Our own reading: the build reads the whole collection, and it fails if stored documents that have the field already clash.

Run them in this order. The dropIndex page describes dropping an index by its name or key pattern:

db.users.dropIndex("email_1")
db.users.createIndex({ email: 1 }, { name: "email_1", unique: true, partialFilterExpression: { email: { $exists: true } } })

Only if you need to back out: the next block drops the partial index, which leaves email unenforced until the original is rebuilt, and recreates the original; it applies only when users-indexes-before.txt shows email_1 as exactly { email: 1 } with unique: true and no other options such as a collation. If the saved file shows more, recreate the index from the definition in that file instead.

Disruptive step: the next two commands drop the partial unique index email_1 and rebuild the original unique index on the whole collection. Until the rebuild finishes nothing enforces uniqueness, and the rebuild fails if documents that share an email were written meanwhile.

db.users.dropIndex("email_1")
db.users.createIndex({ email: 1 }, { name: "email_1", unique: true })

Example (illustrative): On db01, appdb.users has a unique index email_1 and already holds one user without an email. A nightly import script sends 12,400 rows with insertMany and the default ordered: true. Row 7,311 has no email, so the import stops with E11000 duplicate key error collection: appdb.users index: email_1, and 7,310 rows (7,311 - 1) are stored. findOne({ email: { $exists: false } }) returns the one document that lacks the field. The team confirms that users without an email are allowed, saves the index list, and replaces email_1 with the partial unique index above. They then load the remaining 5,090 rows (12,400 - 7,310) from row 7,311 on.

Confirm the fix

  1. Repeat the write or the createIndex that failed. It completes without error 11000.
  2. db.users.getIndexes() shows the index you expect, with unique: true and, if you narrowed it, the partialFilterExpression.
  3. Re-run the aggregation from the proof section. It returns no rows.

What to watch afterwards

  • Log the keyValue field that comes with each 11000 error, so a recurring clash names its value.
  • Check any script that supplies its own _id. The insertMany page says the _id "must be unique within the collection to avoid duplicate key error".
  • Before adding a unique index to a collection with data, run the aggregation above. The unique index page says MongoDB cannot build the index if the data "would violate the unique constraint".

Risks and limits

  • These commands have not been run or lab-tested.
  • A deletion by _id is only as safe as the dump behind it, which is why the check for users.bson comes before the delete.
  • A restored document that clashes with a newer document on a unique key fails with the same error.
  • Dropping a unique index and building its replacement is a window without enforcement, on a collection that may still be taking writes.
  • The message wording is the r8.0.4 server text. The 8.0 insertMany page prints dup key: { : 13.0 }, while the r8.0.4 server source writes the field name into the key, so the key in your message may or may not show a field name. Our own reading: the page example predates the source change.

Sources