English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Limit and Skip Methods in MongoDB

In this chapter, we will learn how to use MongoDB Limit. If you need to read a specified number of data records in MongoDB, you can use MongoDB's Limit method, which accepts a numeric parameter specifying the number of records to read from MongoDB.

MongoDB Limit() method

To read a specified number of records in MongoDB, you need to uselimit()This method. This method accepts a numeric type parameter, which is the number of documents you want to display.

Syntax

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

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

Example

Assuming the collection myycol has the following data.

{_id: ObjectId("507f191e810c19729de860e1")}, title: "MongoDB Overview"},
{_id: ObjectId("507f191e810c19729de860e2")}, title: "NoSQL Overview"},
{_id: ObjectId("507f191e810c19729de860e3"), title: "w3codebox Overview"}

The following example will only display two documents when querying documents.

12)
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
>

If not inlimit()If the number parameter is specified in the method, it will display all documents in the collection.

MongoDB Skip() Method

In addition to the limit() method, there is another methodskip()Also accepts numeric type parameters and is used to skip the number of documents.

Syntax

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

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

Example

The following example will only display the second document.

11).skip(1)
{"title":"NoSQL Overview"}
>

Please note that,skip()The default value in the method is 0.