Geolocation queries
Geolocation is in-built into MongoDB, and is one of its distinguishing features. We have seen examples of 2d
or 2dsphere
index in earlier chapters, and also seen how we can use the near
criterion. Using $geoNear
, that is, the geo_near
method we can get geospatial criteria easily.
One of the common problems in geospatial search is that the queries use radians and not distance units (kilometers, or miles). MongoDB provides a distanceMultiplier
operator that we can use to ensure consistency.
So, this query will give results with the distance in miles:
Author.geo_near([ 50, 13 ]).distance_multiplier(3959)
Tip
The earth has a radius of approximately 3,959 miles or 6,371 km.
Suppose, we find all authors within a 10 miles radius of [34.052923, -84.44399]. First and foremost, when using only latitude and longitude, using a 2dsphere
index is recommended. So, let's modify the Author
model.
class Address include Mongoid::Document ... field :location, type: Array # the location co...