Open this lesson in your favourite AI. It'll walk you through the why, explain the demo, and quiz you on the try-it list.
MongoDB ships two specialist index types that open up query patterns impossible with standard B-trees: text indexes for natural-language keyword search with stemming and stop-word removal, and 2dsphere indexes for proximity queries like 'find all restaurants within 2km of this GPS coordinate'. These capabilities matter because the alternative — pulling data into Elasticsearch or PostGIS — adds operational complexity, synchronization lag, and consistency risk. For applications where full-text or geo requirements are modest, MongoDB's built-in support is often enough, and understanding the limitations (one text index per collection, no relevance scoring tuning) helps you decide when to stay native vs. reach for a specialist.
Create a text index for product search and a 2dsphere index for location-based queries.
name and description. Search for a word that appears in only one field. Then search for a phrase in double quotes. Note how phrase search differs from keyword search in results.Use these three in order. Each builds on the one before.
Explain MongoDB's text search. What is a text index, what does it store, and what does the $text query operator do?
How does MongoDB's 2dsphere index store coordinates internally? What is the difference between $near and $geoWithin, and when would you use each?
I need relevance-ranked text search with field boosting (title matches should outrank description matches). MongoDB text search doesn't support field boosting. What are my options?
package main
import (
"context"; "fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
client, _ := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
stores := client.Database("demo").Collection("stores")
// Create 2dsphere index
stores.Indexes().CreateOne(context.TODO(), mongo.IndexModel{
Keys: bson.D{{"location", "2dsphere"}},
})
stores.InsertMany(context.TODO(), []interface{}{
bson.D{{"name", "Coffee House"}, {"location", bson.D{{"type", "Point"}, {"coordinates", bson.A{-73.9857, 40.7484}}}}},
bson.D{{"name", "Tea Garden"}, {"location", bson.D{{"type", "Point"}, {"coordinates", bson.A{-73.9900, 40.7500}}}}},
})
// Stores within 1km of Times Square
filter := bson.D{{"location", bson.D{{"$near", bson.D{
{"$geometry", bson.D{{"type", "Point"}, {"coordinates", bson.A{-73.9857, 40.7580}}}},
{"$maxDistance", 1000},
}}}}}
cursor, _ := stores.Find(context.TODO(), filter)
var results []bson.M
cursor.All(context.TODO(), &results)
for _, r := range results { fmt.Println(r["name"]) }
}go run main.go