MongoDB limit() method

MongoDB limit() function is used to specify the maximum number of results to be returned. Only one parameter is required for this function, which is the number of documents that you want to be displayed. This improves the performance and prevents the MongoDB from returning a large number of results than required for processing.

Syntax of limit() method

Here is the basic syntax of limit() method -

db.collection.find().limit(number)

It accepts only one argument, i.e., the number of the result. It is a positive integer that specifies the maximum number of the result returns.



Example of limit() method

Suppose, we have following 'students' collection.

{ "_id" : ObjectId("60d1860b3379d41d51aa7133"), "name" : "Jorz Rai", "age" : 10, "class" : "5A" }
{ "_id" : ObjectId("60d1860b3379d41d51aa7134"), "name" : "Rana Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("60d1860b3379d41d51aa7135"), "name" : "Andy Joya", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("60d1860b3379d41d51aa7136"), "name" : "Mary Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("60d1860b3379d41d51aa7137"), "name" : "Priska Somya", "age" : 12, "class" : "6A" }
mongodb limit

The following query returns only three documents of the 'students' collection.

db.students.find().limit(3);
Output of the above code:
{ "_id" : ObjectId("60d1860b3379d41d51aa7133"), "name" : "Jorz Rai", "age" : 10, "class" : "5A" }
{ "_id" : ObjectId("60d1860b3379d41d51aa7134"), "name" : "Rana Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("60d1860b3379d41d51aa7135"), "name" : "Andy Joya", "age" : 11, "class" : "5C" }
mongodb limit





Read more articles


General Knowledge



Learn Popular Language