Working with Geospatial Queries

1. Storing GeoJSON Objects

TypeExample
Point{type:"Point", coordinates:[lng, lat]}
Polygon{type:"Polygon", coordinates:[[[lng,lat],...]]}
Index2dsphere on the field

2. Storing Legacy Coordinates

FormIndex
[lng, lat]2d or 2dsphere
{lng, lat}Field-order embed (legacy 2d)

3. Using $near for Proximity Queries

FieldEffect
$geometryGeoJSON Point
$maxDistanceMeters (2dsphere)
$minDistanceMeters
ResultSorted nearest-first
db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [-73.97, 40.77] }, $maxDistance: 1000 } } });

4. Using $nearSphere for Spherical Distance

AspectDetail
FormSame as $near but always spherical
2d indexDistances in radians; 2dsphere = meters

5. Using $geoWithin for Boundary Queries

FormEffect
$geometry: PolygonInside polygon
$centerSphere: [[lng,lat], radians]Circle on sphere
$box, $polygon, $centerLegacy flat shapes
Result orderNot sorted

6. Using $geoIntersects for Intersection

AspectDetail
Form{$geoIntersects: {$geometry: ...}}
UseMatch geometries crossing input
Requires2dsphere index

7. Using $centerSphere for Circular Regions

FieldDescription
Center[lng, lat]
RadiusRadians (divide meters by 6378100)

8. Using $box for Rectangular Regions

FormEffect
$geoWithin: {$box: [[lng1,lat1],[lng2,lat2]]}Flat bounding box (2d only)

9. Using $polygon for Custom Shapes

FormEffect
$geoWithin: {$polygon: [[lng,lat], ...]}Flat polygon (2d)
ModernUse GeoJSON Polygon with 2dsphere

10. Calculating Distances

StageDetail
$geoNear (aggregation)Returns docs with computed distanceField
distanceMultiplierConvert meters to other units
includeLocsAdd matched location field
keySpecify geo field when multiple exist
db.places.aggregate([
  { $geoNear: { near: { type: "Point", coordinates: [-73.97, 40.77] }, distanceField: "dist", maxDistance: 5000, spherical: true } }
]);

11. Understanding Geospatial Query Limitations

LimitDetail
$near + shardedUse $geoNear stage instead
$near returns sortedCan't combine with $sort easily
Antipodal polygonsSplit into smaller pieces