Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 70 ยท CRUD: create and read

Sorting, Limiting and Skipping

Learn MongoDB sort, limit and skip: ascending and descending order, tie-breaking, pagination with skip, why large skips are slow and range-based pagination.

A query without a sort has no promised order. When a screen shows "the ten newest posts" or "page 3 of the results", you need three cursor methods: sort to put documents in order, limit to cap how many come back, and skip to jump over the first ones. Together they give you top-N lists and pagination.

This lesson explains how each one works, a few traps (ties, mixed types, the order of the calls), and why the obvious way to paginate gets slower on deep pages. The cure is range-based pagination, which you will build step by step. Basic filters are in Finding Documents, and the effect of indexes on sorting is in How Indexes Work.

The mongosh listings are real MongoDB commands and are read-only. The runnable examples use the JavaScript practice engine from The Practice Engine Used in This Tutorial, which applies sort, skip and limit to an array of documents. It is a stand-in, not a database, so it cannot show real timings.

Three cursor modifiers

sort 1 ascending, -1 descending.
limit Return at most n documents.
skip Jump over the first n documents.
1 / 2

Sorting

sort takes a document that lists fields and a direction: 1 for ascending, -1 for descending.

JavaScript
db.players.find().sort({ score: -1 })               // highest score first
db.players.find().sort({ team: 1, score: -1 })      // by team, then best score first

With several fields, MongoDB sorts by the first, and uses the next one only to order documents that are equal on the previous ones. The order of fields in the sort document therefore matters.

Ties are not stable

If two documents have the same sort value, MongoDB does not promise which comes first, and the order can change between runs, especially across pages. The fix is to end every sort with a field that is unique, usually _id:

JavaScript
db.players.find().sort({ score: -1, _id: 1 })

Now the order is fully determined. Skipping this detail is a classic cause of pagination bugs, where a document appears on two pages or on none.

Mixed types and missing fields

Sorting works on any values, and different types sort in a fixed order. For the types you meet most often, from smallest to largest: missing and null, numbers, strings, embedded documents, arrays, ObjectIds, booleans, dates. A document with no value for the sort field sorts as null, so it comes first in an ascending sort and last in a descending one.

For an array field, an ascending sort uses the smallest element of each array and a descending sort uses the largest.

JS Sort directions, ties and mixed types

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the first line, Eli (no score) and Fay (null) come before every number, and Gus's string "n/a" comes after all the numbers. In this stand-in, ties such as Ana and Dev keep their insertion order. Real MongoDB makes no such promise, which is exactly why the tie-break line matters.

Limit and skip

limit(n) returns at most n documents, and skip(n) discards the first n before returning any:

JavaScript
db.posts.find().sort({ createdAt: -1 }).limit(10)             // newest ten
db.posts.find().sort({ createdAt: -1 }).skip(20).limit(10)    // third page of ten

A few details:

  • The order of the calls does not matter. .limit(10).skip(20).sort(...) behaves the same as the version above. MongoDB always sorts first, then skips, then limits.
  • limit(0) means no limit, the same as leaving it out.
  • Without a sort, limit and skip are unreliable, because the underlying order is not promised. Always sort when you paginate.
  • A sort that cannot use an index happens in memory, and the server stops it with an error if it needs more than about 100 MB. A suitable index lets the server read documents already in order, which is also much faster. See Designing Compound Indexes.
  • A limit combined with a sort lets the server keep only the top n documents while it works, so "top 10" is cheap even on a large collection.

Pagination with skip

The classic way to build "page p with size items per page" is:

JavaScript
db.posts.find(filter).sort({ createdAt: -1, _id: -1 })
        .skip((p - 1) * size).limit(size)

It is simple and it allows jumping to any page. It also has two weaknesses.

It gets slower on deep pages. To skip 100,000 documents the server still has to walk past them, one by one, even if it uses an index. The cost grows with the page number, so page 1 is fast and page 5,000 is slow. At the scale of a few hundred pages you will not notice. At the scale of millions of documents, you will.

It can show duplicates or miss items when data changes. If a new document is inserted while a user moves from page 2 to page 3, everything shifts by one position, so the last item of page 2 appears again at the top of page 3.

Range-based pagination

Instead of counting how many documents to skip, remember where you stopped and ask for documents after that point. If you sort by _id, the next page is simply:

JavaScript
db.posts.find({ _id: { $gt: lastIdSeenOnPreviousPage } })
        .sort({ _id: 1 }).limit(size)

With an index on the sort field the server jumps straight to the starting point, so every page costs the same. Inserts do not shift your position either, because you hold a value, not a count.

When you sort by a field that is not unique, such as score, use the pair (score, _id) as the position. For a descending score sort, the next page is "lower score, or same score and a larger _id":

JavaScript
db.players.find({
  $or: [
    { score: { $lt: lastScore } },
    { score: lastScore, _id: { $gt: lastId } }
  ]
}).sort({ score: -1, _id: 1 }).limit(size)

The price is that you can only move to the next page (or previous, with the opposite comparison), not jump to page 87. Many feeds and "load more" lists need nothing else. When you need page numbers on a modest collection, skip is fine.

JS Skip pages vs range pages

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both approaches return the same three pages here. The difference shows up in the work done: the skip version reads past more documents for each page, while the range version starts from the saved position. The number in parentheses is the count of documents the server would walk past; this stand-in does not measure time.

Practical advice

  • Always combine limit and sort when you want "top N", and give the sort a unique last key.
  • Keep an index that matches your sort. Without it, large sorts are slow and may hit the memory limit.
  • Use skip for small, page-numbered lists. Use range-based pagination for feeds, exports and anything that might get deep.
  • Return an opaque "cursor" or "next page token" from your API that holds the last seen values, so clients do not need to understand the query.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In what order does MongoDB apply these calls: find(f).limit(10).skip(20).sort({ a: 1 })?

    The server always sorts first, then skips, then limits, no matter how you chain the calls.
  2. 2. Why should a paginated sort end with a unique field such as _id?

    Documents with equal sort values may come back in any order. A unique last key makes the order deterministic, which avoids duplicates and gaps across pages.
  3. 3. What is the main drawback of skip(100000) for pagination?

    The cost of skip grows with the number skipped. Range-based pagination avoids it by starting from the last seen value.
  4. 4. You sort ascending on a field that is missing in some documents. Where do those documents appear?

    A missing value sorts like null, which is lower than numbers and strings, so those documents come first in an ascending sort.

Summary

  • sort({ field: 1 }) orders ascending and -1 descending; with several fields, later ones break ties among earlier ones.
  • Without a unique last key, the order of ties is not guaranteed; end the sort with _id.
  • MongoDB always applies sort, then skip, then limit, whatever order you chain them in.
  • skip pagination is simple but gets slower on deep pages and can show duplicates when data changes.
  • Range-based pagination filters on the last seen value (a compound (field, _id) position for non-unique sorts) and costs the same on every page, with an index on the sort fields.

Next, reach inside documents with Querying Nested Fields and Arrays.