MongoDB Limit Documents

MongoDB Limit Documents – To limit the number of records that a query returns in the result, use cursor.limit() method. Limit method accepts a number as argument which indicates the limit on number of records in the query result.

In this tutorial, we shall learn how to limit the number of records that a query returns in the result using examples.

Syntax of limit method

The syntax of limit method is

cursor.limit(N)

When no value is provided, all the records are fetched, else the value provided in the argument would be considered.

Note : db.collection.find() returns cursor to the records. And limit() method can be applied on this cursor to limit the number of records as shown below :

db.collection.find().limit(N)

Example 1 – Limit Documents in Query

In this example, we will limit the number of documents in the result by passing a number as argument to limit() method.

> db.people.find().limit(2)
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb2"), "name" : "Midhuna", "age" : 23, "place" : "Amaravati" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb3"), "name" : "Akhil", "age" : 24, "place" : "New York", "bonus" : 250 }

Only two documents, as provided to the limit method, are fetched in the result.

Example : limit() method Default Operations

If no integer is provided as argument to limit() method, then it returns all the documents for the query.

> db.people.find().limit()
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb2"), "name" : "Midhuna", "age" : 23, "place" : "Amaravati" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb3"), "name" : "Akhil", "age" : 24, "place" : "New York", "bonus" : 250 }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb4"), "name" : "Honey", "age" : 27, "profession" : "Docter" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb5"), "name" : "Manju", "age" : 28, "place" : "Vizag", "profession" : "Driver" }

All documents are fetched in the result.

Conclusion

In this MongoDB TutorialMongoDB Limit Documents, we have learnt to limit the number of documents returned in the result. In our next tutorial, we shall learn to skip first N documents of a query.