Unique Index | MongoDB Indexing Tutorial
Compound Index | MongoDB Indexing Tutorial
Index Performance | MongoDB Indexing Tutorial
Indexing Types | MongoDB Indexing Tutorial
Unique Index | MongoDB Indexing Tutorial
List Indexes | MongoDB Indexing Tutorial
Create Index | MongoDB Indexing Tutorial
What is a unique index in MongoDB?
A unique index is an index that enforces unique values for a given field.
Using a unique index, you can ensure that values for a particular field are unique.
Even popular libraries like Mongoose create unique indexes under the hood to enforce unique validations on Mongo collections...
How does a unique index work under the hood?
A unique index ensures that a given value can be stored only once for a given field. Whenever you create a collection in Mongo, a unique index is automatically created on the _id field. This is what ensures that no two documents with the same _id are stored.
A unique index is enforced before, during, and after creation.
If you have existing data in a collection that isn't unique for a given field then you will get a DuplicateKey error when creating the index in the first place.
This includes the absence of the target field. If a document in your collection is missing field x and you create a unique index on x then you can't add a new document omitting the x field. This is because x missing on two documents is not unique!
Using this same concept, you can ensure uniqueness on other fields. Things like emails, usernames, credit cards, SSN, phone numbers are all strong candidates for uniqueness.
How to create a unique index in MongoDB?
Creating a unique index requires setting the unique flag to true...
db.people.createIndex({email:1}, {unique:true})
Notice how the {unique:true} is an option specified when creating any index.
Now if you try to add two documents with the same value for email you will get a DuplicateKey error.
Note that if your collection already has duplicate values for a field you're trying to create a unique index on, it will throw an error as well.
While this example demonstrates adding the unique flag to a single field index, you can also make a compound index unique...
db.getCollection('people').createIndex({email:1,user:1}, {unique:true})
Now if you try to insert two documents with same value for email AND user, you will get a DuplicateKey error.
Please note you WILL NOT get such error if email is same but user is different for two documents.