Is this query efficient? (using sort ascending after indexing by descending)

I’m using this for Notifications, Messages and Posts:

Posts.rawCollection().createIndex({ feedId: 1, date: -1 });

That way I can do:

Posts.find({feedId, date:{$lt:someDate}}, {limit:10})

But today I realized that to find “greater than”, I need to specify sorting like this:

Posts.find({feedId, date:{$gt:someDate}}, {limit:10, sort:{date:1}})

Otherwise, it doesn’t find the first 10 searching forwards from that date, but the first 10 searching backwards from the last date.

Today I read in S.O. that changing the sorting order in a collection with compound indexes is inefficient, and I was wondering if you had experience with something like this.

https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/

you sort on only one field. There is no problem, it will works with both sort: {date: 1} and sort: {date: -1}

1 Like