Geospatial Queries — MongoDB Technical Interview Questions & Answers

Querying by location with 2dsphere indexes.

Geospatial Queries

  • Simple meaning: Store GeoJSON points, create a 2dsphere index, then find places near a point.
  • How to use: { loc: { type: "Point", coordinates: [lng, lat] } } — longitude first. db.places.createIndex({ loc: "2dsphere" }). $near / $geoWithin.
  • Common mistake: latitude first (GeoJSON is [lng, lat]). Missing 2dsphere index.
  • Interview tip: GeoJSON + 2dsphere + lng,lat order.

Technical Interview Tip: Coordinates are longitude, latitude.

Code Examples for Geospatial Queries

Geospatial Queries — working example

db.places.createIndex({ location: "2dsphere" })
db.places.insertOne({
  name: "Cafe",
  location: { type: "Point", coordinates: [73.8567, 18.5204] } // [lng, lat]
})
db.places.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [73.85, 18.52] },
      $maxDistance: 2000
    }
  }
})

Geospatial Queries — geoJSON points use [longitude, latitude]; 2dsphere indexes power $near / $geoWithin.

How to Explain Geospatial Queries to an Interviewer

GeoJSON coordinate order?

Longitude, then latitude