mongodbmongodb-querynosqlaggregation-frameworkmongodb-indexes

Can a query still use an index to sort a field if the index was not the one chosen in the winning plan?


I have a compound index and an index on a single field A. If in a find query, the compound index was chosen as the winning plan, and the results are sorted by the field A, will field A's index be used to sort it?


Solution

  • Unfortunately, no.

    MongoDB cannot use different indexes for sorting and document selection.

    See https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/#use-indexes-to-sort-query-results

    Note that it can use a compound index for sorting, i.e. if the compound index were on {a:1, otherfield:1}, that index can be used for selection by multiple fields, and sorting by a.