In this MongoDB Tutorial, we shall learn to limit the number of records that a query returns in the result.

MongoDB Limit Documents

MongoDB Limit Documents – To limit the number of records that a query returns in the result, use cursor.limit() method. Limit method accepts a number as argument which indicates the limit on number of records in the query result.

Syntax of limit method

Following is the syntax of limit method :

When no value is provided, all the records are fetched, else the value provided in the argument would be considered.

Note : db.collection.find() returns cursor to the records. And limit() method can be applied on this cursor to limit the number of records as shown below :

 

Example : With a number as argument to limit method

Only two documents, as provided to the limit method, are fetched in the result.

 

Example : With nothing provided as argument to limit method

All documents are fetched in the result.

 

Conclusion

In this tutorial – MongoDB Limit Documents, we have learnt to limit the number of documents returned in the result. In our next tutorial, we shall learn to skip first N documents of a query.