Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Unique index vs compound index

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
like image 901
Zaid Masud Avatar asked Mar 07 '12 09:03

Zaid Masud


People also ask

What is MongoDB compound index?

Or in other words, compound indexes are those indexes where a single index field contains references to multiple fields. In MongoDB, the compound index can contain a single hashed index field, if a field contains more than one hashed index field then MongoDB will give an error.

Do MongoDB indexes need to be unique?

Unique Index and Missing FieldBecause of the unique constraint, MongoDB will only permit one document that lacks the indexed field. If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error.

What is unique index in MongoDB?

A unique index ensures that a given value can be stored only once for a given field. Whenever you create a collection in Mongo, a unique index is automatically created on the _id field. This is what ensures that no two documents with the same _id are stored.

Does MongoDB support compound indexes?

MongoDB supports compound indexes, where a single index structure holds references to multiple fields [1] within a collection's documents. The following diagram illustrates an example of a compound index on two fields: MongoDB imposes a limit of 32 fields for any compound index.


1 Answers

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.

like image 144
Remon van Vliet Avatar answered Oct 18 '22 18:10

Remon van Vliet