Mongodb unique index

Unique index is like a unique key contraint in mysql. It prevent duplicate values to be inserted in the collection for the fields with the unique index. If the field that you want to put unique index contraint on it already has duplicate values, you will not succeed until the duplicates are removed.

Create an unique index on the studentId of the students collection.

db.students.createIndex({studentId: 1}, {unique: true});

With the above unique key, if you try to add a document with a studentId that is already in the collection, you will get duplicate key error. For example, assume the studentId 123 is not yet in the collection, the first operation below will succeed but second one will fail.

db.students.insert({studentId: 123});
db.students.insert({studentId: 123});

Search within Codexpedia

Custom Search

Search the entire web

Custom Search