Cache work and limit

Hello

i read the documentation but that is absolute not clear when search in the detail of working query

i have query on periode with index on date 15 days

.getCollection("mycollection").find(
{
    $and:[{"myDateTime":{$gte:"2020-03-01T00:00:00.000"}},
          {"myDateTime":{$lte:"2020-03-15T23:59:59.999"}},
          {"code":"zzzz"},
          {"protocol":"X"}]
		  }
 ).sort({"myDateTime":-1}).limit(200)

first question very important, how work internaly the query with sort and limit

Is the query with sort on index is fulled completed internaly before it execute the limit of 200 on the resultset, or it stop at 200 lines of index reading.

Second question

if i use same query on 15 days period and i execute again on 24h the same query in case of period, is the cache is used if the data is already loaded by the previous query ?

.getCollection("mycollection").find(
{
    $and:[{"myDateTime":{$gte:"2020-03-13T00:00:00.000"}},
          {"myDateTime":{$lte:"2020-03-13T23:59:59.999"}},
          {"code":"zzzz"},
          {"protocol":"X"}]
		  }
 ).sort({"myDateTime":-1}).limit(200)

when i execute i got more than 2s for 15 days, and less 1s for 24h, on 30 million operations with same index sort reading

edit: for this one, i get answer, the response is no

Thanks for answer

Hi,

Is the query with sort on index is fulled completed internaly before it execute the limit of 200 on the resultset, or it stop at 200 lines of index reading.

If you have an index that can answer the query, it will traverse the index and stop at result # 200. Since an index is always sorted, it is relatively cheap to do this operation. Especially if your query is a covered query.

if i use same query on 15 days period and i execute again on 24h the same query in case of period, is the cache is used if the data is already loaded by the previous query ?

Assuming the index/documents are still in the WiredTiger cache, yes it will be reused. The link you posted specifically mentions that MongoDB does not cache query results, but also mentions that it keeps the most recently used data in RAM.

For query indexing in general, you might want to check out my answer on StackOverflow about this topic.

Best regards,
Kevin