9
votes

Assume a hypothetical document with 3 fields:

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

Now, given a query on emailAddress AND account, which of the following two indexes will perform better:

  1. Unique index on emailAddress alone (assume it is a unique field)
  2. Compound index on account and emailAddress
2

2 Answers

18
votes

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.

4
votes

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.