MongoDB Limit () method
To limit the number of records returned in MongoDB, you need to use the limit () method. The method accepts a numeric type parameter, which is the number of documents to display.
Grammar
The basic syntax for the limit () method is as follows:
> DB. Collection_name.find (). Limit (number)
Shell
Example
Assume that the collection Myycol has the following data.
> db.mycol.find ({},{' _id ': 1, ' title ': 1})
{"_id": 101, "title": "MongoDB Guide"}
{"_id": 102, "title": "NoSQL Database"}
{"_id": 104, "title": "Python Quick Guide"}
{"_id": +, "title": "MongoDB Overview"}
The following example displays only two documents when querying a document.
> db.mycol.find ({},{"title": 1,_id:0}). Limit (2)
{"title": "MongoDB Guide"}
{"title": "NoSQL Database"}
If you do not specify the value of the number parameter in the limit () method, it displays all the documents in the collection.
MongoDB Skip () method
In addition to the limit () method, a method of Skip () also accepts a numeric type parameter, which is used to skip the number of documents.
Grammar
The basic syntax for the Skip () method is as follows-
>db. Collection_name.find (). Limit (number). Skip (number)
Example
The following example displays only a third document.
> db.mycol.find ({},{"title": 1,_id:0}). Limit (1). Skip (2)
{"title": "Python Quick Guide"}
Note that the default value in the Skip () method is 0.
MongoDB Limit number of records