Duplicate key error — unique index constraint violated
This error occurs when an insert or update operation attempts to create a document with a value in a unique-indexed field that already exists in another document. It is MongoDB's primary mechanism for enforcing uniqueness.
- 1Inserting a document with a value that already exists in a unique-indexed field
- 2An `update` with `upsert:true` that would create a duplicate in a unique index based on its query
- 3Concurrent `insertOne` operations racing to insert a document with the same unique key value
- 4A multi-document transaction that attempts to insert the same unique key twice
An insert operation on a collection with a unique index on the `email` field receives a duplicate value.
db.users.createIndex({ email: 1 }, { unique: true })
db.users.insertOne({ email: "alice@example.com", name: "Alice" })
db.users.insertOne({ email: "alice@example.com", name: "Alice B." })expected output
MongoServerError: E11000 duplicate key error collection: mydb.users index: email_1 dup key: { email: "alice@example.com" }Fix 1
Use `updateOne` with `upsert` to Avoid Duplicates
WHEN You want to insert a document if it is new, or update it if it exists.
db.users.updateOne(
{ email: "alice@example.com" },
{ $set: { name: "Alice C.", updatedAt: new Date() } },
{ upsert: true }
)Why this works
`updateOne` with `{ upsert: true }` atomically finds a document matching the filter and updates it, or inserts a new document if no match is found. This is the standard pattern for 'insert-or-update' logic.
Fix 2
Catch the Error and Handle Gracefully
WHEN Duplicate key errors are an expected part of the application logic.
try {
await collection.insertOne(doc);
} catch (err) {
if (err.code === 11000) {
console.log("Document already exists, skipping insert.");
} else {
throw err; // Re-throw other errors
}
}Why this works
In some cases, you may want to attempt an insert and simply move on if it fails due to a duplicate. Catching the specific error code `11000` allows the application to react specifically to uniqueness violations without crashing.
Fix 3
Query Before Writing
WHEN You need to know if the document exists to perform different logic.
const existingUser = await db.users.findOne({ email: "alice@example.com" });
if (existingUser) {
// Logic for existing user
} else {
// Logic for new user
}Why this works
Checking for the document's existence before attempting to insert it. This pattern is less atomic and can lead to race conditions in highly concurrent systems, but can be useful for conditional logic.
✕ Drop the unique index to silence the error
This is a critical anti-pattern. Removing the unique index allows duplicate data to be inserted, which corrupts application data integrity and can lead to serious bugs. The index is there for a reason.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev