MongoDB – Limit Records

MongoDB – Limit Records

In this chapter, we will learn how to limit records using MongoDB.

The Limit() Method

To limit the records in MongoDB, you need to use limit() method. The method accepts one number type argument, which is the number of documents that you want to be displayed.


The basic syntax of limit() method is as follows −



Consider the collection myycol has the following data.

{ "_id" : 0, "name" : "aimee Zank", "class" : 10 }
{ "_id" : 1, "name" : "Aurelia Menendez", "class" : 11 }
{ "_id" : 2, "name" : "Salena Olmos", "class" : 12 }

Following example will display only two documents while querying the document.

> db.stuDetails.find({},{"name":1,"_id":0}).limit(2)
{ "name" : "aimee Zank" }
{ "name" : "Aurelia Menendez" }
If you don't specify the number argument in limit() method then it will display all documents from the collection.
## MongoDB Skip() Method
Apart from limit() method, there is one more method skip() which also accepts number type argument and is used to skip the number of documents.
### Syntax
The basic syntax of skip() method is as follows −


### Example
Following example will display only the second document.

{ "name" : "Salena Olmos" }

Please note, the default value in skip() method is 0.
MongoDB – Projection (Prev Lesson)
(Next Lesson) MongoDB – Sort Records
', { 'anonymize_ip': true });