Working with Geospatial Data
Working with geospatial data in MongoDB
MongoDB supports geospatial data and provides various features for storing and querying location-based data. Geospatial indexes and queries allow you to efficiently perform spatial operations such as finding points within a specific area or determining the distance between points.
Geospatial Indexes
To work with geospatial data, you need to create a geospatial index. MongoDB supports two types of geospatial indexes:
- 2d Index: Suitable for flat, planar surfaces.
- 2dsphere Index: Suitable for spherical surfaces such as the Earth's surface.
Creating a Geospatial Index
Below is an example of creating a 2dsphere index on a location field:
Create Geospatial Index Command
db.places.createIndex({ location: "2dsphere" })
Geospatial Queries
Geospatial queries in MongoDB allow you to perform operations such as finding documents near a specific point, within a specific area, or within a specific shape.
Example: Finding Documents Near a Point
Below is an example of using the $near operator to find documents near a specific point:
$near Query Example
db.places.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [ -73.9667, 40.78 ]
},
$maxDistance: 1000
}
}
})
Example: Finding Documents Within a Polygon
Below is an example of using the $geoWithin operator to find documents within a polygon:
$geoWithin Query Example
db.places.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [
[
[ -73.97, 40.77 ],
[ -73.95, 40.77 ],
[ -73.95, 40.75 ],
[ -73.97, 40.75 ],
[ -73.97, 40.77 ]
]
]
}
}
}
})
