6 min read
•Question 18 of 27hardHow do you handle geospatial queries in MongoDB?
Location-based queries.
What You'll Learn
- GeoJSON format
- Geospatial indexes
- Location queries
GeoJSON Format
code.jsJavaScript
{
name: "Coffee Shop",
location: {
type: "Point",
coordinates: [-73.97, 40.77] // [longitude, latitude]
}
}Create Geospatial Index
code.jsJavaScript
// 2dsphere for Earth-like sphere
db.places.createIndex({ location: "2dsphere" });
// 2d for flat surfaces
db.places.createIndex({ location: "2d" });Find Near
code.jsJavaScript
// Find places near a point
db.places.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [-73.97, 40.77]
},
$maxDistance: 5000 // 5km in meters
}
}
});Find Within Area
code.jsJavaScript
// Within a polygon
db.places.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [[
[-73.99, 40.75],
[-73.95, 40.75],
[-73.95, 40.79],
[-73.99, 40.79],
[-73.99, 40.75]
]]
}
}
}
});
// Within a circle (legacy)
db.places.find({
location: {
$geoWithin: {
$centerSphere: [[-73.97, 40.77], 5 / 6378.1] // 5km radius
}
}
});Aggregate with $geoNear
code.jsJavaScript
db.places.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [-73.97, 40.77] },
distanceField: "distance",
maxDistance: 5000,
spherical: true
}
},
{ $limit: 10 }
]);