A spatial index accelerates queries based on geographic location, distance, or spatial relationships. In MongoDB, it avoids scanning large geographic datasets and supports applications such as maps, geolocation services, and spatial analytics. section 7.2.6
Choose the index type according to the geometry your queries interpret:
- Use a 2dsphere index for queries interpreting geometry on an earthlike sphere, including proximity, area, and coordinate queries. section 7.2.6
- Use a 2d index for queries interpreting coordinates on a flat plane. section 7.2.6
- Store 2dsphere values as GeoJSON objects or legacy coordinate pairs; validate longitude from -180 to 180 and latitude from -90 to 90. section 7.2.6
{
"type": "Point",
"coordinates": [40.7128, -74.0060]
}
Use this GeoJSON Point structure as the location value for a 2dsphere-indexed field. section 7.2.6
Find nearby shipwrecks
Create a 2dsphere index on the coordinates field, then query for shipwrecks within 5 kilometers of the specified point. MongoDB requires a geospatial index for $near, $nearSphere, and $geoNear operations. section 7.2.6
db.shipwrecks.createIndex({ coordinates: "2dsphere" })
Create the 2dsphere index used by the nearby-shipwreck query. section 7.2.6
db.shipwrecks.find({
coordinates: {
$near: {
$geometry: { type: "Point", coordinates: [-79.9081268, 9.3547792] },
$maxDistance: 5000
}
}
})
Run a proximity query with a GeoJSON point and a 5,000-meter maximum distance. section 7.2.6
