MongoDB Spatial Indexing: Geospatial
MongoDB Spatial Indexing: Geospatial
MongoDB Spatial Indexing: Geospatial
Tip: 2dsphere Index
$collection->createIndex(['location' => '2dsphere']);
Required for all geospatial queries.
Gotcha: GeoJSON Format
'location' => [
'type' => 'Point',
'coordinates' => [longitude, latitude],
]
Tip: Polygon Search
$collection->find([
'location' => [
'$geoWithin' => [
'$geometry' => [
'type' => 'Polygon',
'coordinates' => [[[...]]],
],
],
],
]);
Gotcha: Coordinate Order
Always [longitude, latitude]. Not [latitude, longitude].
Tip: Near Query with Distance
['$geoNear' => [
'near' => ['type' => 'Point', 'coordinates' => [-73.97, 40.77]],
'distanceField' => 'distance',
'maxDistance' => 5000,
]]
Gotcha: Index Required
Without 2dsphere index, geospatial queries do full collection scans.
Tip: Embed or Reference? The 80/20 Rule
If you always access data together, embed it. If you access it independently, reference it. The 16MB document size limit is the hard boundary — stay under 1MB for most documents.
Tip: Index Your Query Patterns, Not All Fields
Creating indexes on every field wastes RAM. Use explain() to find in-memory sorts and collection scans. Index only what your actual queries filter on.
Gotcha: No Transaction Rollback for Index Builds
Building an index on a large collection can take hours. If it fails midway, the partial index is silently discarded. Plan index builds during maintenance windows.
Senior Insight
MongoDB's geospatial queries are excellent for location-based features. I've built near-real-time location tracking using 2dsphere indexes and $nearSphere queries. The key performance insight: $nearSphere requires a 2dsphere index and always returns results sorted by distance. If you need to combine geospatial with other filters (like category or status), create a compound index with the 2dsphere as the first field.
Source: MongoDB Developer Center (https://www.mongodb.com/developer/), MongoDB Engineering Blog (https://www.mongodb.com/blog/channel/engineering-blog), Studio 3T Blog (https://studio3t.com/blog/)