Limit records in MongoDB

To limit the records in MongoDB, you need to use the limit () method. The limit () method takes a parameter in a numeric format, which is the Document number you want to display.

Limit () method in MongoDB

To limit the records in MongoDB, you need to use the limit () method. The limit () method takes a parameter in a numeric format, which is the Document number you want to display.

Syntax

The basic limit () method syntax is as follows:

 > db . COLLECTION_NAME . find (). limit ( NUMBER ) 

For example

You follow Collection with the name mycol with the following data:

 { "_id" : ObjectId ( 5983548781331adf45ec5 ), "title" : "MongoDB Overview" } { "_id" : ObjectId ( 5983548781331adf45ec6 ), "title" : "NoSQL Overview" } { "_id" : ObjectId ( 5983548781331adf45ec7 ), "title" : "Tutorials Point Overview" } 

The following example shows only 2 Documents while querying.

 > db . mycol . find ({},{ "title" : 1 , _id : 0 }). limit ( 2 ) { "title" : "MongoDB Overview" } { "title" : "NoSQL Overview" } > 

If you do not specify the parameter in the limit () method, it will display all Documents from that Collection.

Skip () method in MongoDB

In addition to the limit () method, there is another method in MongoDB: skip () also takes a parameter in the numeric form and is used to jump over the specified Document number.

Syntax

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

 > db . COLLECTION_NAME . find (). limit ( NUMBER ). skip ( NUMBER ) 

For example

The following example will only display the second Document.

 > db . mycol . find ({},{ "title" : 1 , _id : 0 }). limit ( 1 ). skip ( 1 ) { "title" : "NoSQL Overview" } > 

Remember that the default value in skip () is 0.

According to Tutorialspoint

Previous article: Projection in MongoDB

Next lesson: Arrange records in MongoDB

You've just finished reading the article "Limit records in MongoDB" edited by the TipsMake team. You can save limit-records-in-mongodb.pdf to your computer here to read later or print it out. We hope this article has provided you with many useful tech tips and tricks. You can search for similar articles on tips and guides. Thank you for reading and for following us regularly.

« PREV Sort records in MongoDB
NEXT » Projection in MongoDB