MongoDB

Stage 2 · Lesson 5 of 9

Sorting, skip, limit and cursors

Reading and writing documents

find returns a , an object that fetches results in as you read them, rather than the whole result at once. Chain sort({ year: -1, _id: 1 }) to order it (1 ascending, -1 descending), limit(n) to cap it and skip(n) to jump past results.

The server always applies sort, then , then limit, whatever order you chain them in. Without sort, the order is not guaranteed and can change. When paging, add a unique such as _id as the last sort key, so ties come back in a stable order.

Large skip values get slower, because the server still walks past every skipped document; the application stage shows a better method.

Common trapa "latest ten" query with limit(10) and no sort.

A question to check yourself, an AI practice session and 2 cheat sheet entries come with the full roadmap. Unlock

Resources for this stage

Start with

  • CourseFree
    MongoDB University

    MongoDB

    Free: the CRUD lessons on inserting, finding, replacing, updating and deleting documents, with labs

Practise

  • Test filters and updates on your own sample documents and share the link when you get stuck

Keep handy

Mark this stage as not done?