Skip to content
M

MongoDB Indexing and Query Performance: A Developer Guide

How indexes work, compound index order, using explain, avoiding collection scans and the null-matching gotchas that surprise people.

Md. Nazim Uddin

Updated Oct 25, 20262 min read0 views

Share
MongoDB Indexing and Query Performance: A Developer Guide
On this page

A query that takes 5 ms with 1,000 documents can take seconds with a million. Indexes are the difference.

What an index does

Without an index, MongoDB scans every document in the collection. An index is a sorted structure that lets it jump straight to matches, the way a book index points to pages.

Create indexes for how you query

If you often filter posts by status and sort by date:

db.posts.createIndex({ status: 1, publishedAt: -1 });

In Prisma, declare it in the schema with @@index([status, publishedAt]).

Compound index order: the ESR rule

Order the fields as Equality, then Sort, then Range. An index on { status, publishedAt } serves "status equals published, newest first" perfectly.

Check with explain

db.posts.find({ status: 'PUBLISHED' }).sort({ publishedAt: -1 }).explain('executionStats');

Look for IXSCAN (good) rather than COLLSCAN (a full scan), and compare totalDocsExamined with the number returned.

Project only what you need

Return only the fields you use. Large text fields on list queries waste memory and bandwidth.

Beware of null and missing fields

In MongoDB, a missing field and an explicit null are different. A filter like deletedAt: null matches documents where the field is null or missing, but ORMs may translate it differently, and range operators on null can behave unexpectedly. Always test soft-delete and cleanup queries on a copy of your data before running them in production.

Do not over-index

Every index slows writes and uses memory. Add indexes for real queries and remove unused ones.

Takeaway

Index for your actual queries, order compound indexes by Equality, Sort, Range, and verify with explain.

Keep reading