Working with Geospatial Indexes

1. Creating 2dsphere Index

FormUse
createIndex({location: "2dsphere"})Spherical Earth queries
Field typeGeoJSON object or [lng, lat]

2. Creating 2d Index

AspectDetail
FormcreateIndex({location: "2d"})
UseFlat coordinate planes (legacy)
BoundsDefault [-180, 180]; customizable

3. Understanding Index Differences

Feature2dsphere2d
ModelSpherical (Earth)Flat plane
GeoJSONYesNo
$nearSphereYesYes
$geoWithin polygonsYesLimited
RecommendationModern appsLegacy / game grids

4. Indexing GeoJSON Objects

TypeExample
Point{type:"Point", coordinates:[-73.97,40.77]}
LineString{type:"LineString", coordinates:[[...],[...]]}
Polygon{type:"Polygon", coordinates:[[[...]]]}
MultiPoint / MultiPolygonStandard GeoJSON
Coordinate order[longitude, latitude]

5. Setting Coordinate Precision

Option (2d)DefaultEffect
bits26Geohash precision (1-32)
min / max-180/180Coordinate range

6. Creating Compound Geospatial Index

FormUse
{location:"2dsphere", category:1}Filter category + nearest
Geo position2dsphere can be anywhere in compound

7. Understanding Geospatial Index Limits

LimitDetail
Polygon verticesNo hard cap, but performance degrades >10k
Coordinate validation2dsphere requires valid lat/lng (±90, ±180)
Self-intersecting polygonsRejected

8. Optimizing Geospatial Queries

TipEffect
Use $geoWithin + $centerSphereCheaper than $near for unsorted results
Combine with filterCompound index reduces scanned docs
Limit early$near returns sorted; .limit() saves work