MongoDB Limit Query Results

By Yashwant Chavan, Views 1428, Last updated on 03-Mar-2019

In this tutorial you will learn how to limit the query result set using mongoDB. mongoDB cursor limit() method is used to limit the cursor records, specify a numeric value to limit the documents.

tags MongoDB

Limit the number of Documents - db.collection.find().limit()

The basic syntax of limit() method is as follows.

 db.collection.find().limit( NUMBER );

Insert few documents into students collection

> db.students.insert(
 [
  { roll_no: 1, first_name: "Yashwant",last_name: "Chavan",class : "X"},
  { roll_no: 2, first_name: "Dinesh",last_name: "Patil",class : "X"},
  { roll_no: 3, first_name: "Mahesh",last_name: "Sonar",class : "X"},
  { roll_no: 4, first_name: "Kapil",last_name: "Deshpande",class : "X"},
  { roll_no: 5, first_name: "Vinayak",last_name: "Bhide",class : "X"}
 ]
);

BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 5,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

> db.students.find();
{ "_id" : ObjectId("57f87bbf97b545992f67fdd8"), "roll_no" : 1, "first_name" : "Yashwant", "last_name" : "Chavan", "class" : "X" }
{ "_id" : ObjectId("57f87bbf97b545992f67fdd9"), "roll_no" : 2, "first_name" : "Dinesh", "last_name" : "Patil", "class" : "X" }
{ "_id" : ObjectId("57f87bbf97b545992f67fdda"), "roll_no" : 3, "first_name" : "Mahesh", "last_name" : "Sonar", "class" : "X" }
{ "_id" : ObjectId("57f87bbf97b545992f67fddb"), "roll_no" : 4, "first_name" : "Kapil", "last_name" : "Deshpande", "class" : "X" }
{ "_id" : ObjectId("57f87bbf97b545992f67fddc"), "roll_no" : 5, "first_name" : "Vinayak", "last_name" : "Bhide", "class" : "X" }
>

In below example , It will display only two documents.


> db.students.find().limit(2)

{ "_id" : ObjectId("57f87bbf97b545992f67fdd8"), "roll_no" : 1, "first_name" : "Yashwant", "last_name" : "Chavan", "class" : "X" }
{ "_id" : ObjectId("57f87bbf97b545992f67fdd9"), "roll_no" : 2, "first_name" : "Dinesh", "last_name" : "Patil", "class" : "X" }

>

Zero limit Value - A limit() value of 0 is equals to no limit

Negative limit Value - A negative limit is similar to a positive limit but closes the cursor after returning a single batch of results

Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]