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.
- 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.
Syntax:
cursor.limit()
Or
db.collectionName.find(<query>).limit(<number>)
Examples:
In the following examples, we are working with:
Database: w3wiki
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.
Contact Us