liveBook · Manning

Spatial index

As explained in MongoDB 8.0 in Action, Third Edition

A geospatial index is an index structure that accelerates queries based on geographic location, distance, or spatial relationships.

A spatial index accelerates queries based on geographic location, distance, or spatial relationships. In MongoDB, it avoids scanning large geographic datasets and supports applications such as maps, geolocation services, and spatial analytics. section 7.2.6

Choose the index type according to the geometry your queries interpret:

  • Use a 2dsphere index for queries interpreting geometry on an earthlike sphere, including proximity, area, and coordinate queries. section 7.2.6
  • Use a 2d index for queries interpreting coordinates on a flat plane. section 7.2.6
  • Store 2dsphere values as GeoJSON objects or legacy coordinate pairs; validate longitude from -180 to 180 and latitude from -90 to 90. section 7.2.6
{
   "type": "Point",
   "coordinates": [40.7128, -74.0060]
}

Use this GeoJSON Point structure as the location value for a 2dsphere-indexed field. section 7.2.6

Find nearby shipwrecks

Create a 2dsphere index on the coordinates field, then query for shipwrecks within 5 kilometers of the specified point. MongoDB requires a geospatial index for $near, $nearSphere, and $geoNear operations. section 7.2.6

db.shipwrecks.createIndex({ coordinates: "2dsphere" })

Create the 2dsphere index used by the nearby-shipwreck query. section 7.2.6

db.shipwrecks.find({
  coordinates: {
    $near: {
      $geometry: { type: "Point", coordinates: [-79.9081268, 9.3547792] },
      $maxDistance: 5000
    }
  }
})

Run a proximity query with a GeoJSON point and a 5,000-meter maximum distance. section 7.2.6

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Explains 2dsphere and 2d choices, data formats, required operations, commands, proximity queries, and coordinate limits without query-engine internals.
Examples
Uses a GeoJSON point, MongoDB shipwreck coordinates, createIndex commands, and $near queries with maximum distances.
What it assumes
Assumes basic MongoDB indexing and document-query familiarity while specifying geographic formats and coordinate bounds.
What you can do after
Apply it via MongoDB commands to index geographic fields and retrieve nearby records efficiently.
How it connects
Connects spatial indexes with GeoJSON, legacy coordinate pairs, 2dsphere indexes, 2d indexes, proximity queries, and aggregation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.