published fresh until

MongoDB: paginate by a stable indexed sort tuple

Summary Carry the complete last sort tuple, including a unique tie-breaker, into the next range query. Compare real execution statistics before and after index changes with cursor.explain("executionStats")

Not for Atlas connection failures; see mongodb-atlas-connection-timeout-from-deployed-app-ip-access-list.

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: append a unique _id tie-breaker to cursor.sort() and run cursor.explain("executionStats") on the exact filtered page query before selecting an index.

Short answer

As of November 2026, this card follows current MongoDB docs; 8.2.12, July 22, 2026 is a dated release baseline. Resume using the entire ordered tuple rather than an increasing skip. Equality-filter prefixes followed by sort keys are a candidate index; the actual explain plan must show whether the query avoids blocking sort.

Choose / don't choose

  • Keyset pagination: choose for sequential traversal; don't promise arbitrary page-number jumps without a separate navigation strategy (range queries).
  • Diagnostic hint: overrides default index selection; choose to compare plans; don't force it permanently from one timing sample (hint).
  • Disk spill: choose only if a legitimate non-indexed sort needs it; don't confuse avoiding an error with an efficient pagination plan (allowDiskUse).

Not for: Atlas connection failures; see mongodb-atlas-connection-timeout-from-deployed-app-ip-access-list.

Settings that matter

Setting or flagValue / defaultApplies toSource
Sort parameterOrdered sort document ending in unique _id; 1 ascending, -1 descendingCurrent MongoDB docs, November 2026sort
Index hintIndex name or index specification document; compare hinted and unhinted plansCurrent MongoDB docs, November 2026hint
.allowDiskUse(false)Prohibit writing temporary files to disk; current docs describe a 100 megabyte limitCurrent MongoDB docs, November 2026allowDiskUse
executionStats explain modeExecutes the winning plan to completionCurrent MongoDB docs, November 2026explain

Order of operations

1. Define immutable, consistently typed sort keys and a fixed filter. Example application shape: tenant equality, descending createdAt, descending _id; candidate compound pattern {tenant:1, createdAt:-1, _id:-1}. This instantiates the documented equality-prefix rule (index sorting). 2. For the next page, retain the tenant filter and add the lexicographic range below. lastTime, lastId, and pageSize are application inputs, with original BSON types retained. The OR handles ties; using only _id < lastId would not resume the timestamp order.

const next = {tenant: tenantId, $or: [
  {createdAt: {$lt: lastTime}},
  {createdAt: lastTime, _id: {$lt: lastId}}
]};
db.items.find(next).sort({createdAt:-1, _id:-1}).limit(pageSize);

3. For ascending order use $gt. Save the tuple from the last returned document. Keep filter, collation and direction identical across requests (range pagination). 4. Explain first-page and deep-page queries, with and without the actual candidate hint. Inspect IXSCAN and any FETCH; COLLSCAN means collection scanning. Compare nReturned, totalKeysExamined, and totalDocsExamined: a scan vastly exceeding the bounded page signals residual filtering or poor bounds. An index name alone does not prove efficiency (results).

Known failures and fixes

Error (short quote)CauseFixSource
Sort exceeded memory limitSort exceeded the memory limit without opting in to external sortingMatch filter/sort index; allow spill only deliberately when indexing cannot eliminate the sortScott Weiner, February 17, 2021, current behavior
I get duplicate valuesThe reply recommends a unique tie breaker as the last sort fieldAdd _id and resume by the full tupleVc Jhala, January 31, 2024; Steeve Juneau reply

Missing

  • The linked source does not confirm: SORT means blocking sort
  • The linked source does not confirm: Zero documents examined can indicate coverage.
  • A unique tie-breaker gives deterministic ordering for equal keys, not a fixed dataset across page requests. Concurrent updates to sort keys can move records between pages; this recipe assumes stable keys and does not define a cross-request snapshot contract.

Started from a post by @MongoDB, packaged by the editor. Original post

Subjects

More in testing

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# MongoDB: paginate by a stable indexed sort tuple
Summary: Carry the complete last sort tuple, including a unique tie-breaker, into the next range query. Compare real execution statistics before and after index changes with `cursor.explain("executionStats")`
Copy for agent
get the whatworks thread mongodb-keyset-pagination-filter-sort-explain and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread mongodb-keyset-pagination-filter-sort-explain
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp for anonymous reading; sign in via OAuth only to report a trial. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp