Skip to main content

Command Palette

Search for a command to run...

Mongoose - Add a unique index on an existing collection

The "sparse" option

Updated
1 min read

When you work with MondoDB you often use indexes to optimize your query.

If you want to create a unique index to prevent duplicated entries for a specific field (like email or username for example) on a new collection you can do it by adding the unique option for the field in your model:

email: { type: String, unique: true}

But if:

  • You create a new field in an existing collection or

  • There's already some document in your collection and you want to change the rules of a field

You have to set a default value and use the parse option:

email: { type: String, default: '', unique: true, parse: true}

Otherwise your index will not be setup by MongoDB.

💡
Don't forget to restart your MongoDB server to create the new index.

Details

The sparse option does not include all documents of a collection, only those that have the indexed field (even if the value is null) it basically check for non-empty value.

If you need to check more than the field existence I would suggest you take a look at Partial Indexes.

Sparse Index - MongoDB documentation

Partial indexes - MongoDB Documentation

What I've learned today

Part 5 of 5

This serie gather all the new things I learn on a day to day basis that can be usefull for everyone. It can be about anything, tech, books, people, hack, etc.

Start from the beginning

MongoDB: Join and Format Array of Data

Aggregation pipeline