LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 2616 min read

Text & Geospatial Indexes

Enable full-text search across string fields, and efficient "find nearby" queries using specialized index types.

Text Indexes

A text index enables full-text search across one or more string fields, supporting features like stemming and stop-word filtering that a plain equality match can't provide.

db.articles.createIndex({ title: "text", body: "text" });

Searching with $text

db.articles.find({ $text: { $search: "mongodb indexing" } });
Only One Text Index Per Collection

Unlike other index types, a collection can have at most one text index — though that single index can cover multiple fields, as shown above.

Geospatial Data & GeoJSON

MongoDB represents locations using the GeoJSON format — a point is an object with a type of "Point" and coordinates as [longitude, latitude] (note: longitude comes first, the opposite of the usual "lat/long" spoken convention).

{
"name": "Coffee Shop",
"location": {
"type": "Point",
"coordinates": [-0.1276, 51.5072]
}
}

Creating a 2dsphere Index

db.shops.createIndex({ location: "2dsphere" });

Querying Nearby Locations

$near (or $geoWithin for a bounded area) finds documents close to a given point, sorted by distance automatically.

db.shops.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [-0.1276, 51.5072] },
$maxDistance: 2000, // meters
},
},
});

FAQs

For simple full-text search needs, yes; for advanced relevance tuning, fuzzy matching, and very large-scale search, a dedicated search engine (or MongoDB Atlas Search) is usually a better fit.

It follows the mathematical (x, y) convention rather than the commonly spoken "lat, long" order — a frequent source of confusion worth remembering explicitly.

Summary

Text indexes enable full-text search, and 2dsphere indexes with GeoJSON enable efficient location-based queries. Next, you'll learn to measure and verify index usage with explain().

Next Lesson →

explain() & Query Performance