Advanced Indexing
Beyond basic single-field and compound indexes, MongoDB offers specialized index types for text search, geographic queries, and complex indexing strategies that balance read speed against write cost.
1. Text Indexes
Text indexes enable full-text search across string fields, with support for stemming and relevance scoring.
db.articles.createIndex({ title: "text", content: "text" })
// Search for documents containing "mongodb" or "database"
db.articles.find({ $text: { $search: "mongodb database" } })
// Sort by relevance score
db.articles.find(
{ $text: { $search: "aggregation pipeline" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })
2. Geospatial Indexes
Geospatial indexes support location-based queries — finding nearby points, points within a shape, or intersecting geometries.
// GeoJSON point format
db.stores.insertOne({
name: "Downtown Cafe",
location: { type: "Point", coordinates: [77.5946, 12.9716] } // [longitude, latitude]
})
db.stores.createIndex({ location: "2dsphere" })
// Find stores within 5km of a point
db.stores.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [77.60, 12.97] },
$maxDistance: 5000
}
}
})
3. Wildcard Indexes
Wildcard indexes index all fields (or a subset) dynamically — useful for collections with unpredictable, user-defined schemas.
db.userSettings.createIndex({ "preferences.$**": 1 })
4. TTL (Time-To-Live) Indexes
TTL indexes automatically delete documents after a specified number of seconds — perfect for session data or temporary logs.
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 } // Auto-delete after 1 hour
)
5. Indexing Strategy Considerations
| Consideration | Guidance |
|---|---|
| Write-heavy collections | Minimize indexes — each one slows down writes |
| Read-heavy collections | Index all common query and sort fields |
| Index size | Keep frequently used indexes small enough to fit in RAM |
| Unused indexes | Regularly review with $indexStats and drop unused ones |
6. Advanced Indexing Checklist
- ✅ Create and query text indexes
- ✅ Use 2dsphere indexes for geospatial queries
- ✅ Apply TTL indexes for auto-expiring data
- ✅ Periodically audit index usage with $indexStats
Ready to master MongoDB?
Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.