Fixing Slow MongoDB Queries: Indexes, explain() and Cursor Pagination

By Muhammad Osama Khan, Software Engineer. Performance, Oct 27, 2026, 3 min read.

Read explain() output, build the right compound index and replace skip-based pagination with a cursor. Steps you can repeat on any slow endpoint.

A MongoDB query that feels instant with a hundred documents can crawl with a few million. The usual cause is not MongoDB itself but a query that has to look at every document. The fix is a repeatable routine: measure, add the right index, measure again.

Step 1: measure with explain()

Ask MongoDB how it ran the query. In the shell, or through Mongoose with .explain('executionStats'):

mongosh

db.orders
  .find({ customer: ObjectId('...'), status: 'paid' })
  .sort({ createdAt: -1 })
  .explain('executionStats');

Three things in the result matter:

  • winningPlan.stage: COLLSCAN means a full collection scan; IXSCAN means an index was used.
  • totalDocsExamined against nReturned: if MongoDB looks at 50,000 documents to return 20, you are missing an index.
  • executionTimeMillis: your before and after number.

Step 2: build a compound index with the ESR rule

For a query that filters, sorts and sometimes uses a range, order the index fields as Equality, Sort, Range. Fields you match exactly come first, then the field you sort by, then fields filtered with $gt, $lt or $in-style ranges.

server/models/Order.js

// query: filter by customer and status, newest first
orderSchema.index({ customer: 1, status: 1, createdAt: -1 });

With that index, the filter and the sort are both served by the index: no collection scan and no in-memory sort. Run explain again and compare totalDocsExamined.

Step 3: fetch less data

  • Use a projection to return only the fields the screen needs.
  • Use .lean() for read-only endpoints. Mongoose then returns plain objects instead of full documents, which is faster and uses less memory.
  • Put .limit() on every list query, even when you think the list is short.

server/services/orders.js

const orders = await Order.find({ customer: userId, status: 'paid' })
  .select('status createdAt items.name items.quantity')
  .sort({ createdAt: -1 })
  .limit(20)
  .lean();

Step 4: replace skip with a cursor

skip(n) still walks past n documents, so page 500 is far slower than page 1, and rows that are added or removed while the user pages can appear twice or be missed. A cursor asks for "the next 20 after the last one I saw" instead.

server/services/orders.js

export const listPaid = async (userId, cursor) => {
  const filter = { customer: userId, status: 'paid' };
  if (cursor) filter._id = { $lt: cursor }; // _id is ordered by creation time and always indexed

  const rows = await Order.find(filter).sort({ _id: -1 }).limit(21).lean();

  const hasMore = rows.length > 20;
  const page = hasMore ? rows.slice(0, 20) : rows;
  return { page, nextCursor: hasMore ? page[page.length - 1]._id : null };
};

The client sends ?cursor=<last id> for the next page. We fetch 21 rows to know whether another page exists without a second count query. For sorting by something other than _id, use a compound cursor on that field plus _id as a tiebreaker.

A short checklist

  • Log slow queries: MongoDB Atlas has a Performance Advisor, and self-hosted servers have the profiler.
  • Run explain on the slow endpoint first, not a guess.
  • Index for the query, in ESR order, then verify with explain again.
  • Fetch only what the screen needs, and always limit.
  • Prefer cursors to skip for anything users scroll through.

Frequently asked questions

How do I find out why a MongoDB query is slow?

Run it with explain('executionStats'). Check whether the winning plan is COLLSCAN (a full scan) or IXSCAN (an index), and compare totalDocsExamined with nReturned. Examining thousands of documents to return a few means an index is missing.

What is the ESR rule for MongoDB indexes?

Order the fields of a compound index as Equality, Sort, Range: fields you match exactly first, then the field you sort by, then fields filtered with a range such as $gt or $lt. That lets one index serve the filter and the sort.

Is skip() bad for pagination in MongoDB?

It gets slower on deep pages because the server still walks past every skipped document, and rows added or removed while paging can appear twice or be missed. A cursor ("the next 20 after the last id I saw") stays fast and consistent.

Does Mongoose lean() make queries faster?

It makes read-heavy endpoints cheaper in Node by returning plain objects instead of full Mongoose documents. It does not change how long the database takes to run the query, so fix indexes first.

Keep reading

All articles · Work with me

MO
Muhammad Osama Khan