Working with Geospatial Indexes
1. Creating 2dsphere Index
| Form | Use |
|---|---|
createIndex({location: "2dsphere"}) | Spherical Earth queries |
| Field type | GeoJSON object or [lng, lat] |
2. Creating 2d Index
| Aspect | Detail |
|---|---|
| Form | createIndex({location: "2d"}) |
| Use | Flat coordinate planes (legacy) |
| Bounds | Default [-180, 180]; customizable |
3. Understanding Index Differences
| Feature | 2dsphere | 2d |
|---|---|---|
| Model | Spherical (Earth) | Flat plane |
| GeoJSON | Yes | No |
| $nearSphere | Yes | Yes |
| $geoWithin polygons | Yes | Limited |
| Recommendation | Modern apps | Legacy / game grids |
4. Indexing GeoJSON Objects
| Type | Example |
|---|---|
| Point | {type:"Point", coordinates:[-73.97,40.77]} |
| LineString | {type:"LineString", coordinates:[[...],[...]]} |
| Polygon | {type:"Polygon", coordinates:[[[...]]]} |
| MultiPoint / MultiPolygon | Standard GeoJSON |
| Coordinate order | [longitude, latitude] |
5. Setting Coordinate Precision
| Option (2d) | Default | Effect |
|---|---|---|
| bits | 26 | Geohash precision (1-32) |
| min / max | -180/180 | Coordinate range |
6. Creating Compound Geospatial Index
| Form | Use |
|---|---|
{location:"2dsphere", category:1} | Filter category + nearest |
| Geo position | 2dsphere can be anywhere in compound |
7. Understanding Geospatial Index Limits
| Limit | Detail |
|---|---|
| Polygon vertices | No hard cap, but performance degrades >10k |
| Coordinate validation | 2dsphere requires valid lat/lng (±90, ±180) |
| Self-intersecting polygons | Rejected |
8. Optimizing Geospatial Queries
| Tip | Effect |
|---|---|
| Use $geoWithin + $centerSphere | Cheaper than $near for unsorted results |
| Combine with filter | Compound index reduces scanned docs |
| Limit early | $near returns sorted; .limit() saves work |