Thomas Mitchell
Thomas Mitchell

Reputation: 1071

MongoDB indexes on multiple fields

I've read the chapter on indexes in the MongoDB in action book and was wondering if anyone can expand upon what it talks about regarding indexes.

If I have an index that covers a,b,c,d,e and I query on a,b,c the index is used. What happens if I query on a,c,e? Is the index just used for the query on a or does it get used when querying on the other fields?

In this case does it make more sense to also have the index on a,c,e. I ask because I have a front end piece that links to these fields where users can create a free form query (a,b,c,f could be one). Do I need an index for all possible options that could come through?

Upvotes: 5

Views: 7076

Answers (1)

Sammaye
Sammaye

Reputation: 43884

Compound indexes in MongoDB work via a prefix method.

So for an index of a,b,c,d,e a and a,b would be considered prefixes ( http://docs.mongodb.org/manual/core/indexes/#id5 ), as such querying on both a,b,c and a,c,e should yield an index usage; as to whether a,c,e uses the index performantly is another question entirely.

I ask because I have a front end piece that links to these fields where users can create a free form query (a,b,c,f could be one). Do I need an index for all possible options that could come through?

Hmm if a is always first field defined then probably not (an explain would of course be better here on your dataset), otherwise you may require some combinations, yes.

Upvotes: 6

Related Questions