Open In App

MongoDB – limit() Method

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.

Syntax:



cursor.limit()

Or



db.collectionName.find(<query>).limit(<number>)

Examples:

In the following examples, we are working with:

Database: geeksforgeeks

Collections: gfg

Document: Eight documents contains the content

Limit two documents

db.gfg.find().limit(2)

Here, we only want the first two documents in the result. So, we pass 2 in the limit method.

Limit only two documents that match the given condition

db.gfg.find({"content":/c/i}).limit(2)

Here, we only want the two documents that satisfy the given condition, i.e., {“content”:/c/i}) in the find() method. Here, content is key were we will check whether it contains ‘c’ character in the string or not. /c/ denotes that we are looking for strings that contain this ‘c’ character and in the end of  /c/i, i denotes that it is case-insensitive.

Limit only three documents that match the given condition

db.gfg.find({"content":/c/i}).limit(3)

Here, we only want the three documents that satisfy the given condition, i.e., {“content”:/c/i}) in the find() method. Here, content is key were we will check whether it contains ‘c’ character in the string or not. /c/ denotes that we are looking for strings that contain this ‘c’ character and in the end of  /c/i, i denotes that it is case-insensitive.

Article Tags :