The E11000 duplicate key error occurs when you try to insert a document with a value that already exists in a unique indexed field. This prevents duplicate emails, usernames, or other unique identifiers from being stored in your MongoDB collection.
MongoDB enforces unique index constraints to maintain data integrity. When a field has a unique index, MongoDB guarantees no two documents can have the same value for that field. The E11000 error is thrown when this constraint is violated—meaning you're attempting to insert or update a document with a value that already exists in the indexed field. In the example error, the "email_1" index on the "users" collection already contains a document with email "[email protected]". When MongoDB detects this conflict, it rejects the operation and returns error code 11000 to indicate a duplicate key violation.
The error message shows the index name (e.g., "email_1"). To see all indexes on your collection, run:
db.users.getIndexes()This returns all indexes including their options. Look for { "unique": true } in the index definition.
Query your collection to find documents with the problematic value:
db.users.find({ email: "[email protected]" })If this returns multiple documents, you have duplicates in the collection. If it returns nothing, the value may already be indexed but you're trying to insert again.
Replace direct inserts with upsert operations. Upsert updates the document if it exists, or inserts it if it doesn't:
db.users.updateOne(
{ email: "[email protected]" },
{ $set: { name: "John", email: "[email protected]" } },
{ upsert: true }
)With Mongoose:
await User.findOneAndUpdate(
{ email: "[email protected]" },
{ name: "John", email: "[email protected]" },
{ upsert: true, new: true }
)If you see indexes that don't correspond to your current schema, drop them:
db.users.dropIndex("email_1")Then recreate any indexes you actually need. This is especially important after schema changes or migrations.
Catch the error by checking the error code (11000) and provide user-friendly feedback:
try {
await User.create({ email: "[email protected]", name: "John" })
} catch (error) {
if (error.code === 11000) {
const field = Object.keys(error.keyPattern)[0]
throw new Error(`A user with this ${field} already exists`)
}
throw error
}After fixing the issue, confirm that duplicate values are now properly rejected:
// This should succeed
db.users.insertOne({ email: "[email protected]", name: "Jane" })
// This should fail with E11000
db.users.insertOne({ email: "[email protected]", name: "John" })By default, MongoDB only allows one document to have a null or missing value in a uniquely indexed field. When creating a unique index on existing data with missing values, MongoDB will fail if multiple documents lack the field.
For partial unique indexes (applying only to documents matching a filter), use the partialFilterExpression option:
db.users.createIndex(
{ email: 1 },
{ unique: true, partialFilterExpression: { status: "active" } }
)This allows multiple documents to have the same email if they don't match the filter.
In sharded clusters, unique indexes have special behavior: if the indexed field is not the shard key, uniqueness is only enforced within each shard, not globally across the cluster. If you need global uniqueness in a sharded system, the indexed field must be part of your shard key.
DivergentArrayError: For your own good, using document.save() to update an array which was selected using an $elemMatch projection will not work
How to fix "DivergentArrayError: For your own good, using document.save() to update an array which was selected using an $elemMatch projection will not work" in MongoDB
MongoServerError: bad auth : authentication failed
How to fix "MongoServerError: bad auth : authentication failed" in MongoDB
CannotCreateIndex: Cannot create index
CannotCreateIndex: Cannot create index
StaleShardVersion: shard version mismatch
How to fix "StaleShardVersion: shard version mismatch" in MongoDB
MongoOperationTimeoutError: Operation timed out
How to fix "MongoOperationTimeoutError: Operation timed out" in MongoDB