MongoDB – limit( ) and skip( ) method
In this tutorial we will learn how to use limit() and skip() methods in the MongoDB Query.
The limit() method in MongoDB
This method limits the number of documents returned in response to a particular query.
Syntax:
db.collection_name.find().limit(number_of_documents)
Lets say I want to find out the list of all the department, having the id > 3. I would write a query like this using a criteria:
db.department.find()
{ "_id" : ObjectId("5b3725145eb29c373ddadd52"), "dept_id" : 3, "name" : "Production" }
{ "_id" : ObjectId("5b3bcdb46728a1b55ecec860"), "dept_id" : 4, "name" : "Sales" }
{ "_id" : ObjectId("5b3bced56728a1b55ecec862"), "dept_id" : 5, "name" : "Pre-Sales" }
db.department.find({dept_id : {$gt:3}}).pretty()
OutPut :
{
"_id" : ObjectId("5b3bcdb46728a1b55ecec860"),
"dept_id" : 4,
"name" : "Sales"
}
{
"_id" : ObjectId("5b3bced56728a1b55ecec862"),
"dept_id" : 5,
"name" : "Pre-Sales"
}
Using limit() method to limit the documents in the result:
Lets say I do not want all the documents matching the criteria. I want only selected number of documents then I can use limit() method to limit the number of documents. For example, if I want only one document in output then I would do
this:
db.department.find({dept_id : {$gt:3}}).limit(1).pretty()
OutPut :
{
"_id" : ObjectId("5b3bcdb46728a1b55ecec860"),
"dept_id" : 4,
"name" : "Sales"
}
MongoDB Skip() Method
The skip() method is used for skipping the given number of documents in the Query result.
To understand the use of skip() method, lets take the same example that we have seen above. In the above example we can see that by using limit(1) we managed to get only one document, which is the first document that matched the given
criteria. What if you do not want the first document matching your criteria. For example we have two documents that have student_id value greater than 2002 but when we limited the result to 1 by using limit(1), we got the first document,
in order to get the second document matching this criteria we can use skip(1) here which will skip the first document.
Without using skip():
db.department.find({dept_id : {$gt:3}}).limit(1).pretty()
Output :
{
"_id" : ObjectId("5b3bcdb46728a1b55ecec860"),
"dept_id" : 4,
"name" : "Sales"
}
Using skip:
db.department.find({dept_id : {$gt:3}}).limit(1).skip(1).pretty()
Output :
{
"_id" : ObjectId("5b3bced56728a1b55ecec862"),
"dept_id" : 5,
"name" : "Pre-Sales"
}