MongoDB

18 lessons

Achievements
Combined Shape@2x

The Certificate

avatar

Unique Index

By default, MongoDB creates a unique index on the _id field of each collection. You can also specify the unique option in the options document to create a unique index on a different field or combination of fields.

For example, consider a collection music with a field nirvana that you want to ensure has unique values across all documents. You can create a unique index on the nirvana field like this:

If you try to insert a document with a nirvana field that already exists in the collection, MongoDB will return an error.

Unique indexes enforce the integrity of your data and help you avoid data duplications.