How does MongoDB handle geospatial data?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
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.
Common Mistake
Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real MongoDB project.
Previous
What is the aggregation $group stage and its accumulator operators?
Next
What is the MongoDB connection string format?