Geospatial Queries

MongoDB allows you to store and query location data with high efficiency. This is essential for apps like Uber, Foodpanda, or any store locator.

1. Storing Location Data

Geospatial data is stored using GeoJSON objects. The most common is the "Point".

// Example of a location point (Longitude first, then Latitude)
{
  name: "My Store",
  location: {
    type: "Point",
    coordinates: [ -73.856077, 40.848447 ]
  }
}

2. Creating a Geospatial Index

To perform proximity queries, you MUST create a 2dsphere index.

db.places.createIndex({ location: "2dsphere" })

3. Querying Near a Point

The `$near` operator returns documents from nearest to farthest.

db.places.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [ -73.96, 40.78 ] },
      $maxDistance: 5000 // Distance in meters (5km)
    }
  }
})

4. Finding within a Radius ($geoWithin)

Unlike `$near`, `$geoWithin` does not sort by distance. It just finds all points within a specific area.

db.places.find({
  location: {
    $geoWithin: {
      $centerSphere: [ [ -73.96, 40.78 ], 5 / 3963.2 ] // 5 miles radius
    }
  }
})
Critical Tip: In MongoDB GeoJSON, always list Longitude first, then Latitude. [Lng, Lat]