MongoDB allows you to specify the maximum number of documents to return by making use of the limit() method which will return only the number of documents you need. And as soon as you prepare a MongoDB query for the collection with the help of db.collection.find() method, you can add on the limit() method for specifying the limit.



Without Limit

Here is an example where the Limit method is not used:

Example:

db.writers.find().pretty()

Output:

In the above example, you can see that three results are showing as output.

With Limit

Another example where the Limit method is used:

Example:

db.writers.find().pretty().limit(2)

Output:

In the above example where the limit() method is used, you can see that only two results are seen in the form of output because we have passed the parameter in the limit() method to display only two records.

Skipping Documents

It is also possible to skip some documents from a MongoDB database. You can perform such operations using the skip() method of MongoDB. In other words, it can be said that users have the power to manage or regulate where MongoDB begins returning the query results.

Example:

db.writers.find().pretty().skip(1)

Output:

In the above example where the skip() method is used, you can see that only two results are seen in the form of output because we have skipped the first result.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram