limit
Description
The limit
command restricts the number of documents returned by a query to a specified count. It is typically used after sorting or aggregation operations to retrieve only the most relevant or top results from a larger dataset.
This command is especially useful for performance optimization or for displaying only a subset of high-value results (for example, the top 100 users or the most recent 50 logs).
Note
The limit
command does not guarantee order unless used after an explicit orderby
. If order matters, always pair it with orderby
to ensure predictable results.
Syntax
Example
Use case: Show the top 100 users by activity
Suppose you want to analyze the most active users by counting their log activity. After aggregating and sorting by total hits, you can apply limit
to return only the top 100 users.
Example data
{ "path": "/home", "user": "chris" },
{ "path": "/home", "user": "dave" },
{ "path": "/home", "user": "maya" },
{ "path": "/checkout", "user": "chris" },
{ "path": "/login", "user": "dave" }
{ "path": "/blog", "user": "chris" },
{ "path": "/about", "user": "Eugene" }
Example query
Example output
The limit
command truncates the result set to the first 100 users based on the ordering applied. Since there are only 3 users in this example, all are returned.
Tip
You can achieve similar behavior with the top
command, which combines ordering and limiting in one operation.