0
0
MongoDBquery~5 mins

Geospatial queries basics in MongoDB

Choose your learning style9 modes available
Introduction
Geospatial queries help you find places or points near a location. This is useful for maps and location-based apps.
Finding restaurants near your current location.
Showing nearby stores on a map.
Locating friends or delivery drivers close to you.
Searching for places within a certain distance from a point.
Syntax
MongoDB
db.collection.find({ location: { $near: { $geometry: { type: "Point", coordinates: [longitude, latitude] }, $maxDistance: distance_in_meters } } })
Coordinates are in [longitude, latitude] order, not latitude then longitude.
You must have a geospatial index on the location field to use $near.
Examples
Find places within 5 kilometers of the point with longitude -73.97 and latitude 40.77.
MongoDB
db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [-73.97, 40.77] }, $maxDistance: 5000 } } })
Find places within a small circle around the point. The radius 0.01 is in radians.
MongoDB
db.places.find({ location: { $geoWithin: { $centerSphere: [[-73.97, 40.77], 0.01] } } })
Sample Program
Create a geospatial index, add three places with locations, then find places within 3 km of the point [-73.97, 40.77].
MongoDB
db.places.createIndex({ location: "2dsphere" })
db.places.insertMany([
  { name: "Cafe", location: { type: "Point", coordinates: [-73.97, 40.77] } },
  { name: "Library", location: { type: "Point", coordinates: [-73.98, 40.78] } },
  { name: "Bookstore", location: { type: "Point", coordinates: [-74.00, 40.75] } }
])
db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [-73.97, 40.77] }, $maxDistance: 3000 } } })
OutputSuccess
Important Notes
Always create a 2dsphere index on your location field before running geospatial queries.
Coordinates must be in longitude, latitude order, which is different from many map apps that use latitude, longitude.
The $maxDistance value is in meters when using a 2dsphere index.
Summary
Geospatial queries find data near a location using coordinates.
Use $near with a 2dsphere index to find points close to a given spot.
Coordinates are always [longitude, latitude] in MongoDB geospatial queries.