Limiting 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 : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}

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

{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}

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.


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


Following example will display only the second document.

{"title":"NoSQL Overview"}

Please note, the default value in skip() method is 0.

In MongoDB, the limit() method limits the number of records or documents that you want. It basically defines the max limit of records/documents that you want. Or in other words, this method uses on cursor to specify the maximum number of documents/ records the cursor will return. We can use this method after the find() method and find() will give you all the records or documents in the collection. You can also use some conditions inside the find to give you the result that you want.

  • In this method, we only pass numeric values.
  • This method is undefined for values which is less than -231 and greater than 231.
  • Passing 0 in this method(limit(0)) is equivalent to no limit.






In the following examples, we are working with:

Database: geeksforgeeks
Collections: gfg
Document: Eight documents contains the content