🍃 MongoDB Intermediate

How does MongoDB handle geospatial data?

Answer

MongoDB has native support for geospatial data through GeoJSON objects and specialized indexes that enable location-based queries. GeoJSON format: MongoDB stores geospatial data in GeoJSON format. Point: { type: "Point", coordinates: [-73.97, 40.77] } ([longitude, latitude]). Polygon, MultiPolygon, LineString, etc. also supported. Note: coordinates are always [longitude, latitude], not [lat, lng]. 2dsphere index: for GeoJSON data on a spherical surface (Earth). db.places.createIndex({ location: "2dsphere" }). Handles Earth's curvature for accurate distance calculations. Geospatial operators: $near: returns documents near a point, sorted by distance. db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [-73.97, 40.77] }, $maxDistance: 1000 } } }) — restaurants within 1km; $nearSphere: uses spherical geometry; $geoWithin: documents within a shape (polygon, circle, box) — does not sort by distance, no index required but faster with one; $geoIntersects: documents whose geometry intersects with the given shape; $centerSphere: specify a circle using spherical coordinates for $geoWithin. Aggregation: $geoNear pipeline stage — sorts by proximity, returns distance field. Must be the first stage. Use cases: find nearby restaurants, delivery radius checks, geofencing (is a user inside a zone), store locators, ride-sharing proximity queries. 2d index: for legacy coordinate pairs (not GeoJSON) on a flat surface — limited use.