MongoDB Indexing
Without an index, MongoDB answers a query with a collection scan: it reads every document and checks the filter. That's fine for 20 products, but not for 20 million. An index is a sorted structure (a B-tree) of the values of one or more fields, with pointers to the documents, so the server can jump straight to the matches, and return them already sorted.
Every collection has one index from the start: the unique index on _id.
Creating an index
print(db.products.createIndex({ category: 1 }));
print(db.products.getIndexes().map(ix => [ix.name, ix.key]));category_1
[ [ '_id_', { _id: 1 } ], [ 'category_1', { category: 1 } ] ]
1 means ascending and -1 descending. The default name joins the fields and directions (category_1). For a single field the direction doesn't matter, because an index can be read in both directions.
Seeing the difference
explain('executionStats') reports how a query was executed. Compare the number of documents examined with and without an index:
function stats(filter) {
const s = db.customers.find(filter).explain('executionStats').executionStats;
return { returned: s.nReturned, keysExamined: s.totalKeysExamined, docsExamined: s.totalDocsExamined };
}
print('before:', stats({ tier: 'gold' }));
db.customers.createIndex({ tier: 1 });
print('after: ', stats({ tier: 'gold' }));before: { returned: 3, keysExamined: 0, docsExamined: 12 }
after: { returned: 3, keysExamined: 3, docsExamined: 3 }
Before the index, all 12 customers were read to find 3; afterwards only the 3 matching index keys and documents. The explain() lesson goes deeper.
Compound indexes
An index on several fields is sorted by the first field, then by the second within equal first values, and so on, like a phone book sorted by last name, then first name:
db.orders.createIndex({ status: 1, date: -1 });
// Uses the index for both the filter and the sort:
db.orders.find({ status: 'delivered' }).sort({ date: -1 }).limit(3)
.forEach(o => print(o._id, o.date.toISOString().slice(0, 10)));1014 2026-05-02
1011 2026-04-14
1009 2026-04-03
Rules of thumb for compound indexes (the ESR rule):
- Equality fields first (
status: 'delivered'), - then Sort fields (
date), - then Range fields (
total: { $gt: 50 }).
A compound index also serves queries on its prefixes: { status: 1, date: -1 } helps queries on status alone, but not queries on date alone.
Unique indexes
A unique index rejects duplicate values, just like _id. It is how you guarantee that two customers can't register with the same email:
db.customers.createIndex({ email: 1 }, { unique: true, partialFilterExpression: { email: { $exists: true } } });
try {
db.customers.insertOne({ _id: 13, name: 'Ada Again', email: 'ada@example.com' });
} catch (err) {
print(err.code, err.keyValue);
}
db.customers.insertOne({ _id: 14, name: 'No Email Person' });
print('customers:', db.customers.countDocuments());11000 { email: 'ada@example.com' }
customers: 13
The partialFilterExpression makes the index cover only documents that have an email, so the several customers without one don't collide with each other.
Multikey indexes
Indexing an array field creates one index entry per element (a multikey index). Queries on array elements, like { tags: 'vegan' }, can then use it. MongoDB detects this automatically.
Other index types and options
| Kind / option | Example | Use |
|---|---|---|
| Compound | { status: 1, date: -1 } |
several fields |
| Unique | { email: 1 }, { unique: true } |
prevent duplicates |
| Partial | { partialFilterExpression: { … } } |
index only some documents |
| Sparse | { sparse: true } |
skip documents without the field |
| TTL | { createdAt: 1 }, { expireAfterSeconds: 3600 } |
auto-delete old documents |
| Text | { name: 'text' } |
keyword search (Text Indexes) |
| Geospatial | { location: '2dsphere' } |
near/within queries on coordinates |
| Hashed | { userId: 'hashed' } |
even distribution for sharding |
| Wildcard | { 'attributes.$**': 1 } |
unpredictable field names |
Dropping indexes
db.products.createIndex({ price: -1 });
db.products.createIndex({ rating: -1 }, { name: 'by_rating' });
db.products.dropIndex('price_-1');
print(db.products.getIndexes().map(ix => ix.name));[ '_id_', 'by_rating' ]
The cost of indexes
Indexes aren't free: each one takes memory and disk, and every insert, update and delete must also update every index. Create indexes for the queries your application actually runs, and remove the ones nobody uses ($indexStats shows usage).
Atlas Search. On MongoDB Atlas there is also Atlas Search, a Lucene-based full-text engine with relevance scoring, fuzzy matching and autocomplete, used through the
$searchaggregation stage. It runs only on Atlas (or with the separate search component), so this course uses the built-in text indexes instead.
Test yourself
What does MongoDB do for a query on an unindexed field?
- Refuses the query
- Creates an index automatically
- Scans every document in the collection
- Returns only the first 100 documents
Which queries can use the index { status: 1, date: -1 }?
- Only queries on both fields
- Queries on status, or on status and date, but not date alone
- Queries on date alone
- Any query on the collection
What is the main downside of having many indexes?
- Queries get slower
- Writes get slower and they use memory and disk
- Documents become read-only
- There is none