MongoDB Limit Records

Advertisements


The Limit() Method

To limit the records in MongoDB, you need to use limit() method. limit() method accepts one number type argument, which is number of documents that you want to displayed.

Syntax:

Basic syntax of limit() method is as follows

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

Example

Consider the collection myycol has the following data

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

Following example will display only 2 documents while quering the document.

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

If you don't specify 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 used to skip number of documents.

Syntax:

Basic syntax of skip() method is as follows

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

Example:

Following example will only display only second document.

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

Please note default value in skip() method is 0



Advertisements
Advertisements