I have a Mongo collection with 2 fields, both are dates. I also have the following indexes:
{date1: 1}
{date2: 1}
If I perform the following query it's fast and does an IXSCAN using the date2
index backwards as expected:
db.getCollection('foo').find({ date1: { '$gte': new Date() } }).sort({date2:-1}).limit(50)
However if I reverse the sort order the query becomes very slow and instead uses the date1
index and then sorts the result from the find
part of the query.
I also tried adding an index {date1: 1, date2:1}
which I would expect to be used for both fetching and sorting however this make no difference.
Why is this? I would expect it to use the index for date2
in order to do the limit first in the same way regardless of sort order and I would also expect the compound index to be used.