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.
Index Traversal & IXSCAN vs COLLSCAN Execution Plan
Topic 28: Geospatial 2dsphere Indexes & GeoJSON Spatial Queries
{
"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.
{
"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
db.restaurants.createIndex({ location: "2dsphere" });db.restaurants.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [-73.9857, 40.7484] },
$maxDistance: 2000 // Distance in meters
}
}
});5. Critical Engineering Rules
| Rule / Constraint | Underlying Reason & Impact |
|---|---|
| Coordinate Order | GeoJSON strictly mandates [Longitude, Latitude] order (-180 to 180, -90 to 90). |
| Distance Units | Spherical 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)7. Architectural Trade-offs
- •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
- •Geospatial math is CPU-intensive compared to standard scalar B-Tree comparisons
- •Requires strict adherence to GeoJSON formatting rules
8. Technical Interview Questions
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?