Skip to content
LESSON 28 / 50Intermediateindexing

Geospatial 2dsphere Indexes & GeoJSON Spatial Queries

The 2dsphere index calculates spherical geometries on Earth’s curved surface using GeoJSON objects, powering proximity, polygon containment, and intersection queries.

Interactive Engine Simulator

Index Traversal & IXSCAN vs COLLSCAN Execution Plan

Topic 28: Geospatial 2dsphere Indexes & GeoJSON Spatial Queries

Execution Stage
IXSCAN + FETCH
B-Tree leaf seek
Documents Examined
2
O(log N) lookup
Keys Examined
2
Index keys inspected
Query Latency
0.3 ms
WiredTiger execution time
Explain Plan Output Summary:
{
  "queryPlanner": {
    "winningPlan": {
      "stage": "FETCH",
      "inputStage": {
        "stage": "IXSCAN",
        "indexName": "role_1_country_1",
        "isMultiKey": false,
        "direction": "forward"
      }
    }
  },
  "executionStats": {
    "nReturned": 2,
    "executionTimeMillis": 1,
    "totalKeysExamined": 2,
    "totalDocsExamined": 2
  }
}

1. Formal Definition & Architecture Intent

A 2dsphere index supports geospatial queries on a spherical model of the Earth (WGS84 datum). It indexes GeoJSON geometry objects (Point, LineString, Polygon, MultiPolygon) and executes spatial calculations like $near, $geoWithin, and $geoIntersects.

2. Explain Like I'm 5 (Mental Model)

Instead of treating the world like a flat sheet of paper (which distorts distances), a 2dsphere index treats the Earth like an actual round globe, calculating true distances as airplanes fly.

3. Real-World Architecture Example

Finding all restaurants within 2 kilometers of a user's GPS coordinates.

Sample BSON Documents:
Collection: db.restaurants
{
  "name": "Luigi's Pizza",
  "location": {
    "type": "Point",
    "coordinates": [
      -73.9857,
      40.7484
    ]
  }
}

The $near operator finds matching points sorted by distance from the coordinate.

4. MQL Implementation Steps

Step 1: Create a 2dsphere index on a GeoJSON field
db.restaurants.createIndex({ location: "2dsphere" });
Always requires valid GeoJSON Point structure.
Step 2: Query locations within 2000 meters sorted by proximity
db.restaurants.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [-73.9857, 40.7484] },
      $maxDistance: 2000 // Distance in meters
    }
  }
});
Returns points ordered by geographic distance.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
Coordinate OrderGeoJSON strictly mandates [Longitude, Latitude] order (-180 to 180, -90 to 90).
Distance UnitsSpherical queries ($near, $maxDistance) calculate distance in meters.

6. Deep Dive: The Longitude / Latitude Inversion Trap

The #1 bug in geospatial databases is entering coordinates as [Latitude, Longitude]. GeoJSON follows cartographic [X, Y] Cartesian conventions: X is Longitude (-180 to 180), Y is Latitude (-90 to 90). Inverting them places New York City in the Antarctic Ocean and throws out-of-bounds index errors.

// Valid GeoJSON Point:
// { type: "Point", coordinates: [ -122.4194, 37.7749 ] } // San Francisco (Lng, Lat)
Production Warning: Latitude values exceeding 90 or -90 crash 2dsphere index writes.

7. Architectural Trade-offs

Advantages
  • •Accurate spherical Earth geodesic calculations without flat-projection distortions
  • •Native support for complex polygonal boundary containment ($geoWithin)
  • •Automatically sorts proximity results by distance from origin coordinates
Disadvantages & Gotchas
  • •Geospatial math is CPU-intensive compared to standard scalar B-Tree comparisons
  • •Requires strict adherence to GeoJSON formatting rules

8. Technical Interview Questions

Q1: What is the coordinate order required for GeoJSON Point objects in MongoDB 2dsphere indexes?

GeoJSON strictly requires [Longitude, Latitude] order (X coordinate, then Y coordinate). Reversing the order to [Latitude, Longitude] is a critical error that causes incorrect geographic calculations or out-of-bounds index exceptions.

9. Staff-Level Ready Answer

"The 2dsphere index calculates spherical geometries using GeoJSON (Point, Polygon) on Earth's WGS84 ellipsoid. It requires coordinates in [Longitude, Latitude] order and powers $near, $geoWithin, and $geoIntersects queries measured in meters."

10. Quick Knowledge Check

Which coordinate order is strictly required for GeoJSON points in MongoDB?