Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query near vs. within

Using MongoDB I'm querying homes that are within 25 miles of a lat/long.

My first attempt to do this used the near command, like so:

var near = Query.Near("Coordinates", coordinates.Latitude, coordinates.Longitude, find.GetRadiansAway(), false);
var query = Collection().Find(near);
var listings = query.ToList();

The issue with near is that it only returns 100 listings, whereas I want to return all listings within 25 miles of the coordinates.

My next attempt was to use within:

var within = Query.WithinCircle("Coordinates", coordinates.Latitude, coordinates.Longitude, find.GetRadiansAway(), false);
var query = Collection().Find(within);
var listings = query.ToList();

Within returns all listings within 25 miles, which is great, however it doesn't sort them by how close they are to the center coordinates like near does.

So my question is, how do I get the best of both worlds? How do I get all listings within 25 miles AND have them sorted by proximity to the center coordinates?

like image 765
Justin Avatar asked Mar 30 '11 21:03

Justin


1 Answers

Geospatial $near queries set a default limit() of 100 results. You should be able to get more results by setting a new limit().

While "near" queries are sorted by distance, "within" is not (although "within" doesn't have a default limit).

like image 159
Brendan W. McAdams Avatar answered Nov 19 '22 21:11

Brendan W. McAdams