How to use skip() method in MongoDB

In MongoDB, we can limit the number of documents that we want by using limit() method. This method takes one number and returns only that number of documents. Similar to limit(), we also have another method called skip() to skip the starting values. This method is defined as below :

cursor.skip()

The only parameter offset is a number parameter and it is the number of documents we need to skip. We should use this method before retrieving any document.

In this tutorial, I will show you how to use skip with an example.

Example of using skip() :

Before moving to the skip() example, let’s create one new database, collection and insert a few documents into it :

1. Create one new database :

Open one terminal and use mongod command to run the MongoDB daemon process. Now, open one new terminal window, enter to the MongoDB console using mongo and use the below command to create one database students :

use students

Create one new collection boys in this db :

db.createCollection("boys")

Insert a few documents to this collection :

db.boys.insertMany([{"name": "Alex","age" : 10},{"name": "Bob","age" : 10},{"name": "Albe
rt","age" : 11},{"name": "Chandler","age" : 12},{"name": "Joey","age" : 11}])

mongodb skip example

Now, let’s try to use the skip() method :

Skip the first two :

db.boys.find().skip(2)

mongodb skip example2

Skip first two but show only two results :

db.boys.find().skip(2).limit(2)

mongodb skip example3

Negative value and zero :

mongodbb skip example4

For a negative value, it throws one error and for zero, it will return all results.