Erik
Erik

Reputation: 14750

Which index should I use for $geoWithin searching?

I'm querying documents by their locations with the following criteria

db.collection.find({
    "location": {
        "$geoWithin": {
            "$box": [
                [165.8694369, -52.61941849999999],
                [-175.831536, -29.2313419]
            ]
        }
    }
});

Which index type should I use for location field either 2d or 2dsphere?

Upvotes: 1

Views: 245

Answers (1)

Sede
Sede

Reputation: 61225

Quoting the documentation.

The query calculates distances using flat (planar) geometry.

Changed in version 2.2.3: Applications can use $box without having a geospatial index. However, geospatial indexes support much faster queries than the unindexed equivalents. Before 2.2.3, a geospatial index must exist on a field holding coordinates before using any of the geospatial query operators.

Only the 2d geospatial index supports $box.


Spherical

To calculate geometry over an Earth-like sphere, store your location data on a spherical surface and use 2dsphere index.

Store your location data as GeoJSON objects with this coordinate-axis order: longitude, latitude. The coordinate reference system for GeoJSON uses the WGS84 datum.


Flat

To calculate distances on a Euclidean plane, store your location data as legacy coordinate pairs and use a 2d index.

Upvotes: 1

Related Questions