When a certain query is done on a mongodb collection, if there are multiple indexes that can be used to perform the query, how does mongodb choose the index for the query?
for an example, in a ‘order’ collection, if there are two indexes for columns ‘customer’ and ‘vendor’, and a query is issued with both customer and vendor specified, how does mongodb decide whether to use the customer index or the vendor index?
Is there a way to instruct mongodb to prefer a certain index over another, for a given query?
2
Answers
Their official website states:
You can checkout This article for more information
For your second query, you can try creating custom indexes for documents. Checkout their Documentation for the same
You can generate a query plan for a query you are trying to analyze – see what indexes are used and how they are used. Use the explain method for this; e.g.
db.collection.explain().find()
. The explain takes a parameter with values "queryPlanner" (the default), "executionStats" and "allPlansExecution". Each of these have different plan output.The query optimizer generates plans for all the indexes that could be used for a given query. In your example
order
collection, the two single field indexes (one each for the fieldscustomer
andvendor
) are possible candidates (for a query filter with both the fields). The optimizer uses each of the plans and executes them for a certain period of time and chooses the best performing candidate (this is determined based upon factors like – which returned most documents in least time, and other factors). Based upon this it will output the winning and rejected plans and these can be viewed in the plan output. You will see one of the indexes in the winning plan and the other in the rejected plan in the output.MongoDB caches the plans for a given query shape. Query plans are cached so that plans need not be generated and compared against each other every time a query is executed.
There are couple of ways you can use: