What is Geospatial Data?
Geospatial data represents physical locations on Earth. It's how MongoDB knows that a coffee shop is 2 miles away or that a delivery address is within your service area.
Think of it like a map built into your database. You can store points, lines, and polygons, then query based on distance, area, or proximity.
Geospatial queries power features like ride-sharing apps, store locators, delivery zone validation, and location-based recommendations. If your app deals with "where," geospatial data is your friend.
GeoJSON Objects
MongoDB uses GeoJSON to represent geospatial data. GeoJSON is a standard format for encoding geographic data structures. It supports points, lines, polygons, and more.
The most common GeoJSON type is Point, which represents a single location using longitude and latitude coordinates. Always use [longitude, latitude] order, not the other way around.
MongoDB validates GeoJSON objects, so you can't store invalid coordinates. The longitude must be between -180 and 180, and latitude between -90 and 90.
db.restaurants.insertMany([
{
name: "Downtown Pizza",
location: {
type: "Point",
coordinates: [-73.9857, 40.7484]
},
cuisine: "Italian"
},
{
name: "Harbor Sushi",
location: {
type: "Point",
coordinates: [-73.9934, 40.7505]
},
cuisine: "Japanese"
}
])
Geospatial Indexes
To perform geospatial queries efficiently, you need a geospatial index. MongoDB supports two types: 2d index for flat surfaces and 2dsphere index for spherical geometry.
Use 2dsphere for most real-world applications since the Earth is a sphere. It handles distance calculations correctly across the globe.
The 2d index is useful for things like game maps or other flat coordinate systems where spherical geometry doesn't apply.
db.restaurants.createIndex({ location: "2dsphere" })
db.stores.createIndex({ boundary: "2dsphere" })
db.locations.createIndex({ coordinates: "2d" })
$near and $geoWithin
The $near operator finds documents near a specific point. You give it a coordinate and a maximum distance, and MongoDB returns matching documents sorted by distance.
The $geoWithin operator finds documents within a specific area. You can define the area as a circle, polygon, or box.
These operators use your geospatial index, so they're fast even with millions of documents. Without the index, MongoDB would have to check every document.
db.restaurants.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [-73.99, 40.73] },
$maxDistance: 1000
}
}
})
db.stores.find({
boundary: {
$geoWithin: {
$centerSphere: [[-73.99, 40.73], 0.005]
}
}
})
db.restaurants.find({
location: {
$geoWithin: {
$polygon: [
[-74.00, 40.75],
[-73.98, 40.75],
[-73.98, 40.73],
[-74.00, 40.73]
]
}
}
})