Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Monday, 19 February 2024

Limit Function in MongoDB

In MongoDB, the equivalent of the LIMIT function in SQL is the limit() method, which is used to limit the number of documents returned by a query. Here's how you can use it with an example:


Suppose you have a collection called employees with documents containing fields like employee_id, first_name, and last_name, and you want to retrieve the first 5 employees:


db.employees.find().limit(5)


In this query:

- db.employees.find() selects all documents from the employees collection.

- .limit(5) restricts the result set to only include the first 5 documents.

This query will return the first 5 documents from the employees collection.

You can also specify an optional offset to skip a certain number of documents before limiting the result set. For example, to skip the first 10 documents and retrieve the next 5:

db.employees.find().skip(10).limit(5)

This query will skip the first 10 documents and return the next 5 documents from the employees collection.

Using limit() with skip() allows you to paginate through large result sets efficiently.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.