Labs ICT
Pro Login

$sort and $limit

Ordering and limiting results.

$sort and $limit Stages

Now that you know how to group and filter your data, let's talk about ordering and limiting results. The $sort and $limit stages are like the finishing touches on your data – they make your results presentable and focused.

Think of $sort like organizing your bookshelf. You can arrange books by title, author, or publication date – in ascending or descending order. $limit is like saying "just show me the first 5 books" when you have hundreds.

These stages are often used together to create "Top N" reports – your top 10 customers, best-selling products, or most active users. They're simple but incredibly useful for business analytics.

Sorting Results

The $sort stage orders your documents based on specified fields. Use 1 for ascending order (A-Z, 0-9, oldest to newest) and -1 for descending order (Z-A, 9-0, newest to oldest).

Here's how to sort orders by date and amount:

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $sort: { orderDate: -1, amount: -1 } }
])

This sorts completed orders by date (newest first) and then by amount (highest first) for orders on the same date. It's like having a spreadsheet with multiple sort columns.

You can sort by any field, including computed fields from $group or $project stages. This makes $sort incredibly flexible – you can sort by calculated values, not just raw data.

Limiting Results

The $limit stage does exactly what it sounds like – it limits the number of documents that pass through. It's like saying "only show me the first X results."

This is perfect for creating "Top N" reports or paginating results. Here's an example that gets the top 5 highest-value orders:

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $sort: { amount: -1 } },
  { $limit: 5 }
])

Notice the order: we filter first, then sort, then limit. This ensures we get the 5 highest-value completed orders. If we put $limit before $sort, we'd just sort the first 5 documents – not what we want!

$limit is also useful for performance. If you only need a subset of results, limiting early reduces the amount of data MongoDB needs to process and return. It's like taking a taxi instead of walking – faster and more efficient.

Combining Sort and Limit

The real magic happens when you combine $sort and $limit. It's like having a leaderboard that shows only the top performers. Let's build some practical examples.

Here's how to find your top 10 customers by total spending:

db.orders.aggregate([
  { $group: { 
    _id: "$customerId", 
    totalSpent: { $sum: "$amount" },
    orderCount: { $sum: 1 }
  }},
  { $sort: { totalSpent: -1 } },
  { $limit: 10 }
])

This pipeline groups orders by customer, calculates total spending, sorts by spending (highest first), and returns only the top 10. It's like having a VIP list for your best customers.

You can also use $skip with $limit for pagination. Want results 11-20 instead of 1-10? Add a $skip stage before $limit:

db.orders.aggregate([
  { $group: { _id: "$customerId", totalSpent: { $sum: "$amount" } } },
  { $sort: { totalSpent: -1 } },
  { $skip: 10 },
  { $limit: 10 }
])

This gets you the next page of results. It's perfect for building pagination into your applications – show 10 results per page, and let users navigate through them.

Try it Yourself →