MongoDB Text Search and Geospatial Indexes
On this page
Text and location queries need special indexes
"Products mentioning desk lamp" and "stores within 50 km of this customer" don't fit the sorted-value lookups of Day 7. MongoDB has specialized indexes for both.
MongoDB text search and text indexes
A text index tokenizes string fields into words, removes common stop words, reduces words to their stems ("lamps" → "lamp") and builds an inverted index from words to documents. A collection can have one text index, which can cover several fields with different weights.
db.products.createIndex({ name: "text", desc: "text" }, { weights: { name: 5 } })
db.products.find(
{ $text: { $search: "desk lamp" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })Results on three test products in MongoDB 9:
LED desk lamp score 7.92
Floor lamp score 4.42
Office chair score 0.67 <- matched "desk" in its descriptionTwo things to notice. Words are ORed: "desk lamp" matches anything with either word, ranked by score, so the chair appears. For phrases, quote them ("\"desk lamp\""); to exclude, use -word. And the name weight of 5 lifts products with the words in their name.
Limits: one text index per collection, no fuzzy matching or typo tolerance, basic language support, no autocomplete. For a real search box, use a search engine: MongoDB Search, formerly Atlas Search (Lucene-based, with fuzzy matching, autocomplete, facets and relevance tuning, on Atlas and, since 2026, on self-managed servers) or a separate Elasticsearch/OpenSearch cluster fed by change streams (Day 19).
Geospatial queries with 2dsphere and $geoNear
Store locations as GeoJSON points, longitude first:
db.stores.insertMany([
{ name: "Mitte", loc: { type: "Point", coordinates: [13.4050, 52.5200] } },
{ name: "Potsdam", loc: { type: "Point", coordinates: [13.0645, 52.3906] } },
{ name: "Hamburg", loc: { type: "Point", coordinates: [9.9937, 53.5511] } }
])
db.stores.createIndex({ loc: "2dsphere" })Nearest stores within 50 km, with distances, using $geoNear (it must be the first stage of a pipeline):
db.stores.aggregate([{ $geoNear: {
near: { type: "Point", coordinates: [13.3777, 52.5163] }, // customer near the Brandenburg Gate
distanceField: "dist", maxDistance: 50000 // meters
} }])
// Mitte 1.9 km, Potsdam 25.4 km (Hamburg is beyond 50 km)Other operators:
$nearinfind(): documents sorted by distance.$geoWithin: inside a polygon or circle, unsorted (delivery zones).$geoIntersects: shapes that intersect a given shape.
The 2dsphere index models the Earth as a sphere, so distances are in meters and correct across large areas. The most common bug is swapping latitude and longitude; GeoJSON is [longitude, latitude].
Vector search: finding similar meaning
Text search matches words. Vector search matches meaning: an embedding model turns each product description into a list of numbers, a vector, and a query like "something to hang pictures" finds hooks and nails whose vectors are close to it, even with no words in common. It's the retrieval step behind semantic search and most AI features, including retrieval-augmented generation.
db.products.createSearchIndex("product_vectors", "vectorSearch", {
fields: [
{ type: "vector", path: "embedding", numDimensions: 1536, similarity: "cosine" },
{ type: "filter", path: "category" }
]
})
db.products.aggregate([
{ $vectorSearch: {
index: "product_vectors",
path: "embedding",
queryVector: queryEmbedding, // the query text, embedded with the same model
numCandidates: 200, // neighbors considered by the approximate search
limit: 10, // results returned
filter: { category: "hardware" } // pre-filter on a field declared in the index
} },
{ $project: { name: 1, score: { $meta: "vectorSearchScore" } } }
])Three things decide whether it works well. The query vector must come from the same embedding model, with the same number of dimensions, as the stored vectors. numCandidates trades recall for speed: the search looks at that many approximate neighbors and returns the best limit, and a common starting point is about 20 times limit. And $vectorSearch must be the first stage of its pipeline. It runs on Atlas, and since June 2026 it's generally available for self-managed Community Edition through mongot, a separate search process that runs next to mongod (MongoDB).
Check yourself
Text search ORs the terms by default, and the chair's description contains "desk"; it ranks lower by text score. Quote the phrase for an exact phrase match.
Latitude and longitude are swapped. GeoJSON coordinates are written [longitude, latitude], the opposite of how people usually say them, so [52.5, 13.4] lands far from Berlin. Validate coordinate ranges when storing locations.
When users need search-box features: typo tolerance, autocomplete, facets, synonyms or relevance tuning. MongoDB's text index handles word stemming and basic scoring, which suits simple keyword filtering, not a full search experience.
Vector search: embed the query with the same model used for the product descriptions and run $vectorSearch, which matches on meaning rather than shared words.
Only one, though it can cover several fields with different weights. Plan which fields to include up front, or use a wildcard text index on all string fields.