user3554151
user3554151

Reputation:

Query Points with radius (in meters) in MongoDB

Hi I am am having trouble getting all documents within a radius R (metres) within range of latitude and longitude coordinates X and Y respectively

I am using a 2D legacy index on my collection

db.users.createIndex({'location': '2d'});

I am trying the following:

var users = db.collection('users');
users.find( { location:
                 { $geoWithin
                       { $center
                            [ [ Y, X ], R / 6378100 ]
                    } } });

I am pretty sure it is [Y, X] longitude first then latitude last. 6378100 is the radius of the earth according to google. I have points that should be < 50m apart so R = 50 should find them however I have to make R around 4000 which is rather odd. Any ideas?

Upvotes: 1

Views: 2779

Answers (1)

Sylvain Leroux
Sylvain Leroux

Reputation: 52040

  • With $center, the circle radius is expressed in the same units as your coordinates; it is most useful for flat geometry.
  • With $centerSphere, the circle radius is expressed in radians; it is specifically useful for spherical geometry.

As explained in the MongoDB doc "Calculate Distance Using Spherical Geometry", your conversion function R / 6378100 will convert your radius in radians, and is tailored to use with $centerSphere -- not $center.


Please note that is you want to stick with $center, you have to convert meters to decimal degrees, and that relation is not linear. From an answer by @whuber on GIS, at the equator a routh estimate is "111,111 meters (111.111 km) in the y direction is 1 degree (of latitude) and 111,111 * cos(latitude) meters in the x direction is 1 degree (of longitude)".

Upvotes: 4

Related Questions