MongoDB – limit() and skip() method
In this we are going to learn about limit() and skip() method.
limit() method in MongoDB :
It is used to limit the response on a particular query. −
\\Syntax:- limit the number of documents db.collection_name.find().limit(number_of_documents) ----------------------------- ----------------------------- \\ Example > db.employee.find().pretty() { "_id" : ObjectId("59bf63380be1d7770c3982af"), "employee_name" : "Rajesh", "employee_id" : 2002, "employee_age" : 24 } { "_id" : ObjectId("59bf63500be1d7770c3982b0"), "employee_name" : "Jugal", "employee_id" : 2003, "employee_age" : 25 } { "_id" : ObjectId("59bf63650be1d7770c3982b1"), "employee_name" : "Yash", "employee_id" : 2004, "employee_age" : 23 } \\Using limit() method to limit the documents in the result: > db.employee.find({employee_id : {$gt:2002}}).limit(1).pretty() { "_id" : ObjectId("59bf63500be1d7770c3982b0"), "employee_name" : "Jugal", "employee_id" : 2003, "employee_age" : 25 }
In this example the limit command is used to set the limit of the response because the limit is set to 1 so the output response is also 1.
skip() method in MongoDB :
It is used to skip the number of documents returned in the query result.
. −
\\ Without using skip() > db.employee.find({employee_id : {$gt:2002}}).limit(1).pretty() { "_id" : ObjectId("59bf63500be1d7770c3982b0"), "employee_name" : "Jugal", "employee_id" : 2003, "employee_age" : 25 } \\Using skip: > db.employee.find({employee_id : {$gt:2002}}).limit(1).skip(1).pretty() { "_id" : ObjectId("59bf63650be1d7770c3982b1"), "employee_name" : "Yash", "employee_id" : 2004, "employee_age" : 23 }
In the above example when we do not use skip than the output is employee_id: 2003, but when we use skip then the employee_id: 2003 is skipped and the output will print employee_id: 2004.
Visit :
Discussion