MongoDB Unique Indexes: Enforcing No Duplicate Values
Learn how to create a unique index in MongoDB to prevent duplicate values like emails, how it applies to embedded fields, and how createIndexes() creates several at once.
Unique Indexes in MongoDB
By default, MongoDB happily lets two documents share the same value in any field — including things that logically should be unique, like an email address. A unique index enforces that rule at the database level.
Creating a Unique Index
db.collection.createIndex({ field: 1 }, { unique: true })
db.student.createIndex({ "email": 1 }, { "unique": true })
If duplicate values already exist in the collection, index creation fails:
MongoServerError: Index build failed ... E11000 duplicate key error
collection: rahultechnology.student index: email_1
dup key: { email: "rahul@gmail.com" }
You have to remove or fix the duplicates first, then create the index. Once it exists, any insert or update that would create a duplicate is rejected immediately:
db.student.insertMany([{ roll: 6, name: "rohan", age: 24, email: "rahul@gmail.com" }])
// MongoBulkWriteError: E11000 duplicate key error ... dup key: { email: "rahul@gmail.com" }
Unique Index on an Embedded Field
Indexes work on nested fields too, using dot notation — this also speeds up queries that filter on the embedded field.
db.student.createIndex({ "marks.hindi": 1 })
Once created, a query on marks.hindi uses IXSCAN instead of a full collection scan (see the Indexing Basics lesson for how to verify this with explain()).
Creating Multiple Indexes at Once: createIndexes()
db.student1.createIndexes([
{ roll: 1, email: 1 }
])
// [ 'roll_1_email_1' ]
Common Errors & Troubleshooting
- Index build failing on existing duplicates — you must find and resolve the duplicate values first (e.g. with an aggregation
$group+$match count > 1, covered in the Aggregation section) beforecreateIndex(..., {unique:true})will succeed. - Multiple documents missing the unique field all conflicting with each other — MongoDB treats a missing field as
null, and by default a unique index only allows one document with anull(or missing) value for that field — insert a second one and you'll get a duplicate-key error onnull. - Forgetting a unique index applies per-field, not per-document combination — a single-field unique index only guarantees that one field is unique; use a compound unique index (
{fieldA:1, fieldB:1},{unique:true}) if the combination of two fields together needs to be unique.
Key Takeaways
- MongoDB's default
_idindex is unique — this is the same mechanism applied manually to any field you choose. - Existing duplicates must be cleaned up before a unique index can be created.
createIndexes()(plural) lets you define several indexes in a single call.