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 take an example to understand how to use this method. Lets say, I have a collection studentdata
which has following documents:
> db.studentdata.find().pretty() { "_id" : ObjectId("59bf63380be1d7770c3982af"), "student_name" : "Steve", "student_id" : 2002, "student_age" : 22 } { "_id" : ObjectId("59bf63500be1d7770c3982b0"), "student_name" : "Carol", "student_id" : 2003, "student_age" : 22 } { "_id" : ObjectId("59bf63650be1d7770c3982b1"), "student_name" : "Tim", "student_id" : 2004, "student_age" : 23 }
Lets say I want to find out the list of all the students, having the id > 2002. I would write a query like this using a criteria:
To learn how to specify a criteria while querying documents, read this: MongoDB Query Document
db.studentdata.find({student_id : {$gt:2002}}).pretty()
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.studentdata.find({student_id : {$gt:2002}}).limit(1).pretty() { "_id" : ObjectId("59bf63500be1d7770c3982b0"), "student_name" : "Carol", "student_id" : 2003, "student_age" : 22 }
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.studentdata.find({student_id : {$gt:2002}}).limit(1).pretty() { "_id" : ObjectId("59bf63500be1d7770c3982b0"), "student_name" : "Carol", "student_id" : 2003, "student_age" : 22 }
Using skip:
> db.studentdata.find({student_id : {$gt:2002}}).limit(1).skip(1).pretty() { "_id" : ObjectId("59bf63650be1d7770c3982b1"), "student_name" : "Tim", "student_id" : 2004, "student_age" : 23 }
Leave a Reply