The earlier Indexes lesson covered single-field, compound, and unique indexes — all speeding up an exact or range match. These three types solve genuinely different problems.
Enables searching for words within a text field, rather than matching it exactly — the same kind of search a site's search bar typically needs.
db.articles.createIndex({ title: 'text', body: 'text' })
db.articles.find({ $text: { $search: 'mongodb indexing' } })
// Matches articles containing "mongodb" or "indexing" anywhere in title or body,
// ranked by relevanceThe limits of a text index
A collection can only have one text index, though it can cover multiple fields at once (as above). For search needs beyond this — typo tolerance, weighted relevance tuning — MongoDB Atlas Search (mentioned in the PDF this lesson is based on) is the fuller tool; this covers the built-in basics.
Speeds up queries about location — finding everything within a distance of a point, or inside a boundary.
db.stores.createIndex({ location: '2dsphere' })
db.stores.insertOne({
name: 'Downtown Store',
location: { type: 'Point', coordinates: [-73.99, 40.73] } // [longitude, latitude]
})
// Find stores within 5km of a point
db.stores.find({
location: {
$near: {
$geometry: { type: 'Point', coordinates: [-73.99, 40.73] },
$maxDistance: 5000 // meters
}
}
})A common ordering mistake
GeoJSON coordinates are [longitude, latitude] — the reverse of the [latitude, longitude] order many mapping APIs use. Swapping them silently produces a working query pointed at the wrong place on Earth.
A TTL (Time To Live) index deletes a document automatically once a date field passes a set age — useful for session data, temporary tokens, or logs that shouldn't accumulate forever.
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 } // deleted 1 hour after createdAt
)
db.sessions.insertOne({
userId: 'abc123',
createdAt: new Date(), // this document self-deletes in 1 hour
})| Index type | Use for |
|---|---|
| Text | Searching for words within a text field |
| Geospatial (2dsphere) | Finding documents by location — nearby, within an area |
| TTL | Automatically deleting documents after a set time |