MongoDB – Unique Index
MongoDB allows us to specify a unique constraint on an index. These constraints will prevent an application from inserting documents that have duplicate values for the inserted fields.
Suppose we have a collection named things in a database stuff.
db.stuff.things({"a":"apple"});
A unique index can be created by following command.
db.students.ensureIndex({student_id:1, class_id:1}, {unique:1});
The _id index is also a unique index. When we will try to insert same data in things collection MongoDB will throw a “duplicate key error”.
If we want to add a unique index on two fields then we can do it as follows. Suppose we have students collection and we want to add unique index on student_id and class id fields.
db.students.ensureIndex({student_id:1, class_id:1}, {unique:1});
Removing duplicates when creating unique indexes
We can remove duplicate key when creating an index, we can do this by adding dropDups: true option while adding a unique key index.
db.students.ensureIndex({student_id:1, class_id:1}, {unique:1, dropDups: true});
This option will remove all duplicates except one.