Geospatial indexes
Find documents near a point or inside an area.
Find documents near a point or inside an area with a 2dsphere or 2d index.
Requirements
- A user with
dbAdminorreadWriteon the database. - Locations stored as GeoJSON.
Create the index
JavaScript
db.shops.createIndex({ location: "2dsphere" });Find nearby
JavaScript
db.shops.find({
location: { $near: { $geometry: { type: "Point", coordinates: [-0.376, 39.47] }, $maxDistance: 2000 } },
});Check
The query returns the shops less than 2 km from the point, from nearest to farthest.
Common problems
- A geometry that only touches the edge of the area always counts as inside.