Geospatial queries in MongoDB allow you to perform operations on data that corresponds to points on a surface, such as a map or a plane. Here’s a general step-by-step guide on how to perform such queries.
Step 1: Indexing the Data
Firstly, your appropriate field, typically coordinates, should be indexed as a geospatial index. MongoDB provides two types – 2d for points on a flat plane and 2dsphere for points on a spherical surface (like Earth).
Here is an example:
```
db.collection.createIndex( {
```
Step 2: Storing the Data
Next you should store your geospatial data in a format MongoDB can understand. Two formats are supported: legacy coordinate pairs and GeoJSON objects. Using GeoJSON is generally recommended.
For example:
```
db.places.insert({
name: “Central Park”,
location: { type: “Point”, coordinates: [-73.97, 40.77] }
})
```
Step 3: Querying the Data
Finally, you perform a geospatial query on this data. You will use the $geometry operator.
For example,
Finding Places within a given geometry:
```
db.places.find({
location: {
$geoWithin: {
$geometry: {
type: “Polygon” ,
coordinates: [ [ [ -73.97 , 40.77 ],
[ -73.97 , 40.75 ],
[ -73.98 , 40.75 ],
[ -73.98, 40.77 ] ] ]
}
}
}
})
```
Finding Places near a given point:
```
db.places.find({
location: {
$near: {
$geometry: {
type: “Point” ,
coordinates: [ -73.98 , 40.77 ]
},
$minDistance: 1000,
$maxDistance: 5000
}
}
})
```
Note: Always consult MongoDB manual for a comprehensive understanding of mongodb geospatial querying.