$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[June 06, 2026] MongoDB

MongoDB Geospatial Queries

MongoDB Geospatial Queries: Tips & Tricks

────────────────────────────────────────────────────────

MongoDB Geospatial Queries: Tips & Tricks

Tip: 2dsphere Index

Place::raw(function ($collection) {
    $collection->createIndex(['location' => '2dsphere']);
});

Required for geospatial queries.

Gotcha: Coordinates Are [longitude, latitude]

Not the other way around:

Place::create([
    'name' => 'Office',
    'location' => [
        'type' => 'Point',
        'coordinates' => [-73.97, 40.77], // [lng, lat]
    ],
]);

Tip: Find Nearby Places

Place::raw(function ($collection) {
    return $collection->find([
        'location' => [
            '$near' => [
                '$geometry' => [
                    'type' => 'Point',
                    'coordinates' => [-73.97, 40.77],
                ],
                '$maxDistance' => 5000, // meters
            ],
        ],
    ]);
});

Gotcha: $geoWithin for Polygon Search

'location' => [
    '$geoWithin' => [
        '$geometry' => [
            'type' => 'Polygon',
            'coordinates' => [[[-74, 40], [-73, 40], [-73, 41], [-74, 41], [-74, 40]]],
        ],
    ],
]

Finds places inside a polygon.

Tip: GeoJSON for Complex Shapes

'location' => [
    'type' => 'Point',
    'coordinates' => [-73.97, 40.77],
]

MongoDB supports Point, LineString, Polygon, MultiPolygon.

Gotcha: Distance Calculation

$near returns results sorted by distance. Use $geoNear aggregation for distance in results:

['$geoNear' => [
    'near' => ['type' => 'Point', 'coordinates' => [-73.97, 40.77]],
    'distanceField' => 'distance',
    'maxDistance' => 5000,
]]

Tip: Bounding Box Query

'location' => [
    '$geoWithin' => [
        '$box' => [[-74.0, 40.7], [-73.9, 40.8]],
    ],
]

Finds places within a rectangular area.

Gotcha: No Index = Full Collection Scan

Without a 2dsphere index, geospatial queries scan every document.

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 2dsphere indexes support GeoJSON geometry types and enable geospatial queries. I've built location-based features including near-by search, polygon containment, and distance calculation. The 2dsphere index supports $near, $geoWithin, and $geoIntersects. The important performance detail: 2dsphere indexes are large — a 2dsphere index on a 10M document collection can consume several GB of RAM. Ensure the index fits in your working set.

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/)

────────────────────────────────────────────────────────
<-- back to posts