SyntaxStudy
Sign Up
MongoDB Text and Geospatial Indexes
MongoDB Beginner 1 min read

Text and Geospatial Indexes

MongoDB supports specialised index types beyond B-tree for full-text search and location-based queries. A text index tokenises string fields, removes stop words, and applies stemming, enabling $text search queries that return documents containing specified keywords. Each collection can have only one text index, but it can cover multiple fields with different weights. Geospatial indexes support location queries on GeoJSON objects or legacy coordinate pairs. A 2dsphere index handles queries on a spherical earth model (longitude/latitude) and supports operators like $near, $geoWithin, and $geoIntersects. A 2d index is for flat-plane coordinate systems and is less commonly used today.
Example
// Text index on multiple fields with weights
db.articles.createIndex(
  { title: "text", body: "text", tags: "text" },
  { weights: { title: 10, tags: 5, body: 1 }, name: "articleTextIdx" }
)

// $text search — find articles mentioning "mongodb performance"
db.articles.find(
  { $text: { $search: "mongodb performance" } },
  { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })

// Exclude a word with a minus prefix
db.articles.find({ $text: { $search: "mongodb -sql" } })

// 2dsphere index for GeoJSON
db.locations.createIndex({ coordinates: "2dsphere" })

// Insert a GeoJSON point
db.locations.insertOne({
  name: "Central Park",
  coordinates: { type: "Point", coordinates: [-73.9654, 40.7829] }
})

// $near — find locations within 1 km
db.locations.find({
  coordinates: {
    $near: {
      $geometry: { type: "Point", coordinates: [-73.9654, 40.7829] },
      $maxDistance: 1000
    }
  }
})