MongoDB Skip Documents
MongoDB Skip Documents – To skip first N number of records that a query returns in the result, use cursor.skip() method. Skip method accepts a number as argument which indicates the starting number of records to be skipped in the query result.
In this tutorial, we shall learn to skip a specified number of records that a query returns in the result.
Skipping records is often useful when you have already shown the first N documents, and interested to show only the remaining documents.
Skip command in conjunction with limit command is often used in pagination kind of stuff, where you shown only a limited number of results per page (or fetch).
Syntax of skip method
Following is the syntax of skip method :
cursor.skip(N)
When no value is provided, no documents are skipped, else the value provided in the argument would be considered.
Note : db.collection.find() returns cursor to the records. And skip() method can be applied on this cursor to skip the first N number of records as shown below.
db.collection.find().skip(N)
Example : With a number as argument to skip method
> db.people.find().skip(2)
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb4"), "name" : "Honey", "age" : 27, "profession" : "Docter" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb5"), "name" : "Manju", "age" : 28, "place" : "Vizag", "profession" : "Driver" }
Only two documents, as provided to the skip method, are skipped in the result.
Example 1 – Skip Documents
If no integer is provided as argument to skip() method, no documents will be skipped in the result.
> db.people.find().skip()
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb2"), "name" : "Midhuna", "age" : 23, "place" : "Amaravati" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb3"), "name" : "Akhil", "age" : 24, "place" : "New York", "bonus" : 250 }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb4"), "name" : "Honey", "age" : 27, "profession" : "Docter" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb5"), "name" : "Manju", "age" : 28, "place" : "Vizag", "profession" : "Driver" }
All documents are fetched in the result.
Example 2 – skip() with limit()
In this example, we will use skip() method with limit() method. We shall skip one document and limit to two documents in the result.
> db.people.find().skip(1).limit(2)
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb3"), "name" : "Akhil", "age" : 24, "place" : "New York", "bonus" : 250 }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb4"), "name" : "Honey", "age" : 27, "profession" : "Docter" }
1 document is skipped and the result is limited to 2 documents.
Conclusion
In this MongoDB tutorial – MongoDB Skip Documents, we have learnt to skip first N number of documents that a query returns in the result. In our next tutorial, we shall learn to sort documents.