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.

A unique index can be created by following command.

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.

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.

This option will remove all duplicates except one.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.