MongoDB query faster lte than gte
There are some issues with what you are trying to do:
$or
queries use indexes differentlyFor
$or
queries to be able to use an index, all terms of the$or
query must have an index. Otherwise, the query will be a collection scan. This is described in https://docs.mongodb.com/manual/reference/operator/query/or/#or-clauses-and-indexesToo many indexes in the collection
Having too many indexes in a collection affects performance in more than one way, e.g., insert performance will suffer since you are turning one insert operation into many (i.e. one insert for the collection, and one additional insert for each indexes in your collection). Too many similar-looking indexes is also detrimental to the query planner, since it needs to choose one index out of many similar ones with minimal information on which index will be more performant.
Check the
explain()
output inmongo
shellThe
explain()
output in themongo
shell is the best tool to discover which index will be used by a query. Generally, you want to avoid anyCOLLSCAN
stage (which means a collection scan) andSORT_KEY_GENERATOR
stage (which means that MongoDB is using an in-memory sort that is limited to 32MB, see https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/). Please see Explain Results for more details.
You may want to check out these relevant pages regarding indexing and query performance:
Having said that, I did a quick check in mongo
shell (MongoDB 3.2.8) using your examples. You could try adding these two indexes in your collection:
{blockNumber:1,transactionIndex:1,from:1}{blockNumber:1,transactionIndex:1,to:1}
And drop all the other indexes in the collection. Those two indexes should be able to be used in your two examples queries.