Text Indexes for Keyword Search
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.
// 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.
// 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
1. How many text indexes can a single MongoDB collection have?
2. Which geospatial index type supports GeoJSON Polygon and Point data on a spherical Earth model?
3. What is the correct coordinate order for GeoJSON Point data in MongoDB?
4. Which operator finds documents whose geometry falls entirely inside a given shape?
5. What does a text index do to the words it indexes?
Was this page helpful?
You May Also Like
Indexes in MongoDB
Learn how MongoDB indexes work internally, why they speed up queries, and how to create and manage the core index types.
Compound Indexes
Understand how MongoDB compound indexes combine multiple fields, the ESR rule for ordering keys, and how they support sorting and covered queries.
Performance Tuning Basics
Practical techniques for diagnosing and fixing slow MongoDB queries, covering the profiler, index hygiene, schema design, and working-set memory.