How does a unique index work in MongoDb?

Your thoughts?

Code247 |

A unique index works by ensuring a given field has unique values.

A unique index is not a type of index. Rather it is an option specified when creating an index like this...


This ensures that the indexed field age is unique for the collection.

If you want to ensure that a certain field has no duplicate values, then you have to create an index. This is how popular libraries like Mongoose ensure uniqueness as well. It all boils down to an index in Mongo.

FewerLinesThanYou |

A unique index ensures that only unique values are stored for an indexed field.

To create a unique index, you must specify the unique option like so...

db.collection.createIndex({email:1}, {unique:true})

Notice how a unique index is not it's own type of index. Instead, it is an option you specify when creating an index.

Whether you create a compound index, a single field index, a text index you can add the unique property...


A unique index ensures that only unique values are stored for a given field in a given collection.

theRealJS |

A unique index works by validating that an indexed field has unique values.

MakeMeCTO |

A unique index ensures uniqueness! durr


A unique index works by ensuring unique values for a given field.

When creating an index, you can optionally specify the {unique:true} option...

If a collection already has duplicate values for a given field then you will get errors when you try to create an index with the unique option.

If a collection has multiple documents without a given field and you try to add a unique index you will get errors...this makes sense if you think about it because multiple values can't be "null" for a given field. its all about ensuring uniqueness after all..