MongoDB Limit Documents – limit( ) and skip( ) Method

In this post, we will learn how to use limit() and skip() methods in the MongoDB Query.

The Limit() Method

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

Syntax

The basic syntax of the limit() method is as follows −
> db.COLLECTION_NAME.find().limit(NUMBER)

Example

Consider the collection "posts" has the following data.
> db.posts.find().pretty();
{
        "_id" : ObjectId("5e184a067695f4d696a0598d"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5e184a067695f4d696a0598e"),
        "title" : "NoSQL Database",
        "description" : "NoSQL database doesn't have tables",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 20,
        "comments" : [
                {
                        "user" : "user1",
                        "message" : "My first comment",
                        "dateCreated" : ISODate("2013-12-10T09:35:00Z"),
                        "like" : 0
                }
        ]
}
{
        "_id" : ObjectId("5e18544a7695f4d696a0598f"),
        "title" : "MongoDB CRUD Operations",
        "description" : "MongoDB CRUD Operations",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 20,
        "comments" : [
                {
                        "user" : "user1",
                        "message" : "My first comment",
                        "dateCreated" : ISODate("2013-12-10T09:35:00Z"),
                        "like" : 0
                }
        ]
}
The following example will display only two documents while querying the document.
> db.posts.find({},{"title":1,_id:0}).limit(2);
{ "title" : "MongoDB Overview" }
{ "title" : "NoSQL Database" }
If you don't specify the number argument in the 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 a number type argument and is used to skip the number of documents.

Syntax

The basic syntax of the skip() method is as follows −
> db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

Example

The following example will display only the second document.
> db.posts.find({},{"title":1,_id:0}).limit(1).skip(1);
{ "title" : "NoSQL Database" }
Please note, the default value in skip() method is 0.

Comments