MongoDB - Unique index vs compound index

后端 未结 2 1483
春和景丽
春和景丽 2021-01-05 02:43

Assume a hypothetical document with 3 fields:

  1. _id : ObjectId
  2. emailAddress : string
  3. account : string

Now, given a query on emai

2条回答
  •  旧巷少年郎
    2021-01-05 02:57

    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.

提交回复
热议问题