How to Find Nearby Locations in MongoDB Using Geospatial Queries
To find nearby locations in MongoDB, use a
2dsphere index on your location field and query with the $near operator specifying a point and max distance. This lets MongoDB efficiently return documents ordered by proximity to the given coordinates.Syntax
To find nearby locations, you use a geospatial query with the $near operator on a field indexed with 2dsphere. The query looks like this:
{
locationField: {
$near: {
$geometry: {
type: "Point",
coordinates: [longitude, latitude]
},
$maxDistance: distanceInMeters
}
}
}Here:
locationFieldis the field storing GeoJSON points.$geometrydefines the reference point.$maxDistancelimits results to within this distance in meters.
Make sure the locationField has a 2dsphere index for this to work efficiently.
json
{
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [-73.9667, 40.78]
},
$maxDistance: 5000
}
}
}Example
This example shows how to create a collection with location data, add a 2dsphere index, insert sample locations, and query for nearby places within 5 kilometers.
mongodb
use testdb; // Create collection and insert sample data db.places.insertMany([ { name: "Central Park", location: { type: "Point", coordinates: [-73.9654, 40.7829] } }, { name: "Times Square", location: { type: "Point", coordinates: [-73.9851, 40.7580] } }, { name: "Empire State Building", location: { type: "Point", coordinates: [-73.9857, 40.7484] } } ]); // Create 2dsphere index db.places.createIndex({ location: "2dsphere" }); // Find places near a point within 5 km const nearbyPlaces = db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [-73.985, 40.758] }, $maxDistance: 5000 } } }).toArray(); printjson(nearbyPlaces);
Output
[
{
"_id": ObjectId("..."),
"name": "Times Square",
"location": { "type": "Point", "coordinates": [-73.9851, 40.758] }
},
{
"_id": ObjectId("..."),
"name": "Empire State Building",
"location": { "type": "Point", "coordinates": [-73.9857, 40.7484] }
},
{
"_id": ObjectId("..."),
"name": "Central Park",
"location": { "type": "Point", "coordinates": [-73.9654, 40.7829] }
}
]
Common Pitfalls
Common mistakes when finding nearby locations in MongoDB include:
- Not creating a
2dsphereindex on the location field, which makes queries slow or fail. - Using coordinates in the wrong order; MongoDB expects longitude first, then latitude.
- Not using GeoJSON format (
{ type: "Point", coordinates: [...] }) for location data. - Setting
$maxDistancein the wrong units; it must be in meters.
Example of a wrong query (no index):
db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [40.758, -73.985] }, // latitude and longitude reversed
$maxDistance: 5000
}
}
});Corrected query:
db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [-73.985, 40.758] },
$maxDistance: 5000
}
}
});Quick Reference
| Concept | Description |
|---|---|
| 2dsphere Index | Index type needed for GeoJSON location queries |
| $near | Operator to find documents near a point |
| $geometry | Defines the GeoJSON point for the query |
| $maxDistance | Limits results to within this distance in meters |
| Coordinates Order | Always [longitude, latitude] |
Key Takeaways
Create a 2dsphere index on your location field before running geospatial queries.
Use the $near operator with $geometry and $maxDistance to find nearby locations.
Always store and query coordinates as GeoJSON Points with longitude first, then latitude.
Distances in $maxDistance are measured in meters.
Check your data format and index if queries return no results or are slow.