mongodb unique index vs compound index

mongodb unique index vs compound index  using -'mongodb,mongodb-indexes'

Assume a hypothetical document with 3 fields:

_id : ObjectId
emailAddress : string
account : string

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

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


asked Oct 13, 2015 by maurya
0 votes

2 Answers

0 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.

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

answered Oct 13, 2015 by jekbishnoi
0 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.

answered Oct 13, 2015 by mtabakade