What is Geospatial Index in MongoDB: Explanation and Example
geospatial index in MongoDB is a special type of index that helps efficiently query data based on geographic locations like points, lines, and polygons. It allows fast searches for nearby places or spatial relationships using location data stored in documents.How It Works
Imagine you have a map with many points representing places like restaurants or parks. Searching through all points to find nearby locations would be slow if you check each one. A geospatial index organizes these points in a way that makes searching fast, like grouping nearby places together on the map.
MongoDB supports two main types of geospatial indexes: 2d for flat coordinate data and 2dsphere for spherical data like Earth’s surface. These indexes let MongoDB quickly find documents with locations near a given point or within a certain area, without scanning the entire collection.
Example
This example shows how to create a 2dsphere geospatial index on a collection and query for places near a specific location.
db.places.createIndex({ location: "2dsphere" })
// Insert sample documents
db.places.insertMany([
{ name: "Coffee Shop", location: { type: "Point", coordinates: [-73.97, 40.77] } },
{ name: "Bookstore", location: { type: "Point", coordinates: [-73.88, 40.78] } },
{ name: "Library", location: { type: "Point", coordinates: [-73.95, 40.75] } }
])
// Find places within 5 kilometers of a point
db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [-73.96, 40.76] },
$maxDistance: 5000
}
}
})When to Use
Use a geospatial index when your application needs to handle location-based data and queries. For example, if you build a delivery app, you can find nearby drivers or restaurants quickly. If you have a social app, you can show users events or friends close to their location.
Geospatial indexes are essential for any feature that involves searching by distance, finding points within an area, or analyzing spatial relationships between locations.
Key Points
- Geospatial indexes speed up queries on location data.
- MongoDB supports
2dand2dsphereindex types. 2dsphereis used for Earth-like spherical coordinates.- They enable queries like finding nearby points or points within a polygon.
- Creating the index requires location data in GeoJSON format.