MongoDB - Unique index vs compound index

 ̄綄美尐妖づ 提交于 2019-11-30 20:22:29

In terms of performance the difference will be small at best. Due to the fact that your e-mail addresses are unique any compound index that has an e-mail field will not ever be more helpful than an index on e-mail address alone. The reason for this is that your e-mail field already has maximal cardinality for your collection and any further index fields will not help the database to filter records more quickly since it will always arrive on the correct documents with just the e-mail field.

In terms of memory usage (which is very important for databases like MongoDB) the e-mail index alone is much smaller as well.

TL;DR : Use the index on e-mail address alone.

When it comes to Indexes, the goal is to create a single index with highest possible cardinality (or "selectivity"). Try to write queries that use 1 (compounded) index per query. Unique indexes have maximum cardinality. Compounding unique indexes with less selective fields can not further increase that maximum. Adding more indexes just slows down find(), update() and remove() queries. So be "lean and mean".

However, if you are using sort() on the account field, while doing a find() on the email field, then you should use a compound index:

it's common to query on multiple keys and to sort the results. For these situations, compound indexes are best. http://www.mongodb.org/display/DOCS/Indexing+Advice+and+FAQ

So think it through! If you need to sort data by another field, then you usually need a compound index.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!