mongodbindexingcompound-index

MongoDB compound index usage


Lets say I have document with the following two keys:

1) key1
2) key2

If I am creating compound index on both of them..

{'key1':1,'key2':1}

When running a query relevant only for key1.. does the index above is used? or I need to create specific index only for key1 also?

Thanks


Solution

  • Yes. In a B-tree index, you can use a prefix of the columns.

    So you can use the index for a query on 'key1' (but not as efficiently for 'key2', the column order in the index matters).

    This is the same situation as in a printed telephone book, which is an index on [lastName, firstName]. You can use that to look up people by lastName easily (and not so easily by firstName, but still more efficient than calling everyone and asking for their first name).