Answer the question
In order to leave comments, you need to log in
Why is a selection with a search on a nested field with reverse sort slowing down?
Greetings.
There is a relatively small database of 2.5 million documents. The structure of the documents is not very important, the more it is "dynamic". But there is a query that is executed regularly and quite often - selecting the "most-most" and by the condition of the absence of a nested field:
db.getCollection('special').find({
'checker.updated': { '$exists': false }
}).sort({'postedNum':-1}).limit(1)
db.getCollection('special').find({
'checker.updated': { '$exists': false }
}).sort({'postedNum':1}).limit(1)
Answer the question
In order to leave comments, you need to log in
A good place to start would be to look at the output of explain .
The performance of the application depends on the index used, but in this case you are using $exists: false
, which automatically leads to a full collection scan situation.
Indexing such a field is not an option. If you want to index, then the value must be in the index .
To solve the problem, you need to add something like updated: false
.
If you store a date there, then use an additional field updatedAt
. You should not mix different data types in one field - monga may not build an index.
For reverse sorting, you can create an additional index with reverse order.
You can read more about sorts here https://docs.mongodb.com/manual/tutorial/sort-resu...
You can build a combined index with a forward pass through a property and a reverse sort, just be sure to follow the order.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question