100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
MongoDB

Text and Geospatial Indexes

Learn how MongoDB's text indexes power keyword search and how 2dsphere geospatial indexes enable location-based queries.

Indexing & PerformanceIntermediate10 min readJul 10, 2026
Analogies

A text index tokenizes string field content into individual stemmed words, applying language-aware rules (stemming, case-folding, stop-word removal) so a search for 'running' also matches documents containing 'run' or 'runs'. You create one with db.collection.createIndex({ description: 'text' }) and query it using the $text operator with a $search string; results can be ranked by relevance using the textScore metadata. A collection can have only one text index, though that index can cover multiple fields with individual weights controlling which fields matter more for ranking.

🏏

Cricket analogy: A text index on match commentary is like Cricinfo's ball-by-ball search finding every mention of 'yorker' even when commentary says 'yorkers' or 'yorked', because stemming normalizes word forms.

javascript
// Create a weighted text index across two fields
db.articles.createIndex(
  { title: "text", body: "text" },
  { weights: { title: 5, body: 1 }, name: "ArticleTextIndex" }
);

// Search and sort by relevance score
db.articles.find(
  { $text: { $search: "mongodb performance tuning" } },
  { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });

For production-grade full-text search needs (fuzzy matching, autocomplete, faceting), MongoDB Atlas Search built on Apache Lucene is generally recommended over the basic $text index, which is best suited for simple keyword search within self-managed deployments.

Geospatial Indexes: 2dsphere and 2d

The 2dsphere index supports queries on GeoJSON data (Point, LineString, Polygon) using a spherical model of the Earth, and is the recommended choice for virtually all modern location-based applications. It enables $near (nearest neighbors sorted by distance), $geoWithin (documents inside a shape like a polygon or circle), and $geoIntersects (documents whose geometry intersects a given shape). The legacy 2d index instead handles flat, planar coordinates on a simple x-y grid and is only appropriate for non-Earth coordinate systems like a 2D game map, not real-world geography.

🏏

Cricket analogy: A $geoWithin query on stadium locations within a state polygon is like a broadcaster's map plotting every venue inside Maharashtra using GeoJSON polygons rather than a flat, distorted grid.

javascript
// Store a location as GeoJSON
db.venues.insertOne({
  name: "Wankhede Stadium",
  location: { type: "Point", coordinates: [72.8258, 18.9388] } // [lng, lat]
});

// Create a 2dsphere index
db.venues.createIndex({ location: "2dsphere" });

// Find venues within 5km of a point
db.venues.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [72.8347, 19.0176] },
      $maxDistance: 5000
    }
  }
});

GeoJSON coordinates must be specified as [longitude, latitude], the reverse of the more familiar 'latitude, longitude' convention — swapping them silently produces valid-looking but wildly incorrect query results, often placing points on entirely different continents.

  • Text indexes tokenize and stem string fields, enabling $text/$search keyword queries ranked by textScore.
  • A collection may have only one text index, but it can span multiple weighted fields.
  • 2dsphere indexes support GeoJSON data and spherical Earth queries: $near, $geoWithin, $geoIntersects.
  • The legacy 2d index is for flat, planar coordinates only, not real-world geography.
  • GeoJSON coordinates are ordered [longitude, latitude], the reverse of common convention.
  • MongoDB Atlas Search is recommended over basic $text for advanced full-text search needs.
  • $near results are automatically sorted by distance from the query point.

Practice what you learned

Was this page helpful?

Topics covered

#MongoDB#MongoDBStudyNotes#Database#TextAndGeospatialIndexes#Text#Geospatial#Indexes#Keyword#SQL#StudyNotes#SkillVeris