9. Sorting, Limiting, and Paginating Results

$sort orders documents, $limit restricts the number that continue, and $skip discards the first N documents. Use 1 for ascending and -1 for descending sort order.

For predictable pagination, include a unique tie-breaker such as _id when the main sort field can contain duplicates. Large skip values can be expensive because the server must advance past skipped results. For top-N queries, sort and limit after the calculation that defines the ranking.

A sort before $group can determine the input order for $first and $last; a sort after $group orders the resulting summaries. These have different purposes.

Code Example
db.orders.aggregate([
  { $match: { status: "delivered" } },
  { $unwind: "$items" },
  {
    $group: {
      _id: "$items.productId",
      productName: { $first: "$items.name" },
      unitsSold: { $sum: "$items.quantity" },
      revenue: { $sum: { $multiply: ["$items.quantity", "$items.price"] } }
    }
  },
  { $sort: { revenue: -1, _id: 1 } },
  { $limit: 5 }
]);
Key Takeaways
  • $sort controls order.
  • $limit supports top-N queries.
  • Large $skip values can be expensive.
  • Use a unique tie-breaker for predictable ordering.
Knowledge Check

Why add _id as a secondary sort key for pagination?