How skip() in MongoDB works?

If I am skipping 1000 records [Case 1] and 100000 records [Case 2].
Will Case 2 takes more time ?

Note - I wanted to know in context to using with pagination for my REST API

The only way to know is by looking at the executionTimeMillis in the Explain Plan:

var expl = db.collection.explain("executionStats").aggregate([{$match}, {$skip}])

Hi @Kanav_25090,

The Case 2 will be slower than Case 1 because skip method requires the server to scan from the beginning of the input results set before beginning to return results.

I would recommend you to go through the documentation link below:

Also, definitely give a try to the method suggested by @007_jb to analyse the performance in both cases.

Please let me know if you have any questions.


1 Like

I guess two factors will have an impact on the performance:

  • the batch size of the cursor
  • the number of documents prior to skip()

I wouldn’t imagine there being a sizeable (or even noticeable) difference in performance between 1K and 100K if:

  1. the batch size is >100K and the resultset is relatively small
  2. the number of docs is <= 1K

Despite that, I think skip() is performant enough that you won’t notice a diff between 1K and 100K.

Test, test, test!

1 Like

And I would like to emphasis

It is the best way to learn.