I have a query that searches on two fields: one of those fields is indexed, and one is not.
Will Mongo do the right thing by first searching on the indexed field, and only then searching the other non-indexed search parameter?
It depends.
If you have normal find
, then IXSCAN
will be used on indexed field. You can check this by using explain()
If you have aggregate queries and your first stage matches on non indexed field and second stage uses indexed field, then index will not be used. Here also you can use explain()
to check.
The answer is maybe.
What MongoDB will do is the first time it sees a particular query shape, it will run a short test.
It determines all of the potential index plans that might be used to service the query, including collection scan.
It then runs each of these in parallel, with a limit of 101 documents, 101 units of work, or 100 milliseconds.
The score for each plan is the number of documents found during the test period, divided by the number of units of work required.
After the test, any plan that completed gets bonus points, and additional bonus points if it completed without needing an in-memory sort.
This plan is then cached to be reuse the next time it sees a query with the same shape.
You can run explain with the "allPlansExecution" options to see all of the candidate plans that were considered, and how each compares.
In most cases, it will choose the index as expected, but there are some situations where it doesn't, and explain can be very useful to determine why.