Easy Tutorial
❮ Mongodb Database References Mongodb Php ❯

MongoDB Limit and Skip Methods


MongoDB Limit() Method

If you need to read a specified number of data records in MongoDB, you can use the MongoDB Limit method. The limit() method accepts a numeric parameter that specifies the number of records to read from MongoDB.

Syntax

The basic syntax of the limit() method is as follows:

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

Example

The data in the collection col is as follows:

{ "_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP Tutorial", "description" : "PHP is a powerful server-side scripting language for creating dynamic and interactive websites.", "by" : "tutorialpro.org", "url" : "http://www.tutorialpro.org", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java Tutorial", "description" : "Java is a high-level programming language introduced by Sun Microsystems in May 1995.", "by" : "tutorialpro.org", "url" : "http://www.tutorialpro.org", "tags" : [ "java" ], "likes" : 150 }
{ "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "MongoDB Tutorial", "description" : "MongoDB is a NoSQL database", "by" : "tutorialpro.org", "url" : "http://www.tutorialpro.org", "tags" : [ "mongodb" ], "likes" : 100 }

The following example displays two records from the query document:

> db.col.find({},{"title":1,_id:0}).limit(2)
{ "title" : "PHP Tutorial" }
{ "title" : "Java Tutorial" }
>

Note: If you do not specify a parameter in the limit() method, all data in the collection will be displayed.


MongoDB Skip() Method

In addition to using the limit() method to read a specified number of data, you can also use the skip() method to skip a specified number of data. The skip() method also accepts a numeric parameter as the number of records to skip.

Syntax

The script syntax for the skip() method is as follows:

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

Example

The following example will only display the second document data:

>db.col.find({},{"title":1,_id:0}).limit(1).skip(1)
{ "title" : "Java Tutorial" }
>

Note: The default parameter for the skip() method is 0.

❮ Mongodb Database References Mongodb Php ❯