Ticket: Paging - Limit vs Skip precendence

Hi, when I tried to resolve the problem I found that skip takes precedence over limit. Is the understanding correct?
For example:
Total number of records: 150
cursor.limit(100).skip(20) results in 100 records after skipping the first 20. I was expecting 80 records to be returned.
cursor.limit(80).skip(20) results in the expected 80 records

Hi @Vinoth_57269, welcome back to the community.
Yes, skip will be performed before limit.
The arguments passed to the limit function limits the number of documents returned from the collection based on the query provided.
Therefore, if a certain query results in 150 documents and if you provide 100 as the limit, it will only return 100 documents.
Also, if you provide 200 as the limit only 150 documents will be returned.
Now if you provide an argument to the skip function, MongoDB will perform a skip before the limit.
Hence, for the same query, if you provide 100 as the argument to limit and 20 as argument to skip function, it will return the results from 21st document to 120th document. => 100 documents.
However if you provide 200 as the argument to the limit and 20 as the argument to skip function, it will return the results from 21st document to 150th document in the collection. => 130 documents.

I hope it helps.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

1 Like