Search code examples
mongodbcompound-index

Does query order affect compound index usage


MongoDB compound indexes support queries on any prefix of the index fields, but does the field order in the query must match the order in the compound index itself?

Assuming we have the following index:

{ "item": 1, "location": 1, "stock": 1 }

Does it cover this query:

{"location" : "Antarctica", "item" : "Hamster Wheel"}

Solution

  • Yes. The order/sequence of the fields in the index creation matters.

    In your examples above all the queries that filter on "item" may use the index, but queries that do not use the "item" field and use "location" and or "stock" as your filter condition will NOT use this index.

    The sequence of the fields in the filter in the "read" query does NOT matter. MongoDB is smart enough to know that

    {"location" : "Antarctica", "item" : "Hamster Wheel"}
    

    is the same as

    {"item" : "Hamster Wheel", "location" : "Antarctica"}
    

    As others have pointed out, the best way to ensure that your query is using the index, is to run an explain on your query http://bit.ly/1oE6zo1