MongoDB allows you to create an index on a field with the option of ensuring that it is unique in the collection. In this recipe, we will explore how it can be done.
- Connect to the mongo shell and insert a random document:
use mydb db.testuniq.insert({foo: 'zoidberg'})
- Create an index with the unique parameter:
db.testuniq.createIndex({foo:1}, {unique:1})
The preceding command should give you an output similar to this:
{ "createdCollectionAutomatically": false, "numIndexesAfter": 2, "numIndexesBefore": 1, "ok": 1 }
- Try to add another document with a duplicate value of the field:
db.testuniq.insert({foo: 'zoidberg'})
The preceding command should give you an error message similar to this:
WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error collection: mydb.testuniq index: foo_1 dup key: { : \"zoidberg\" }" } })
- Drop the index...