1

I am working on a small module which deals with the nearby documents for given spherical lookup. While working with mongoid3 I used the following to receive documents with given latitude, longitude and spherical distance to lookup the documents.

document_klass.within_spherical_circle(geo_attribute: [[77.04363, 28.45842], (20.fdiv(6371))])

Gives the result of documents within the 20 kms sphere from the latlong given. Also I can apply limit and pagination on this as this is a pure mongoid criteria.

But the result of this doesn't give documents in the sorted order by default. (and also I am unable to find any option with within_spherical_circle which gives me documents sorted via distance) I also tried geo_near method but with that its hard to do pagination/skip. Any suggestions?

UPDATE

Also, I tried mongoid 3.1.x geo_near method as

document_class.limit(10).geo_near([77.04363, 28.45842]).distance_multiplier(6371).max_distance(10.fdiv(6371)).spherical

which suppose to give me the result in sorted order and its doing exactly the same.

[0.0, 0.013106917278934711, 0.014252314759648424, 0.01842674324658152, 0.02131271009525241, 0.022594202024593005, 0.024637859034323726, 0.02501954892893619, 0.02501954892893619, 0.025071008433970268]

But this doesn't not consider, page for mongodb $skip thing.

r3bo0t
  • 462
  • 4
  • 11

1 Answers1

0

i'm guessing here, if you have a method for distance, you can define something like this in your model

def distance(object_to_calculate_distance)
  self.method(object_to_calculate_distance)
  #method should be the method predefined for distance
end

then use sort_by to order the array like

@array_of_items_in_the_circle.sort_by(&:distance)

hope it helps

Alexis
  • 4,836
  • 2
  • 21
  • 27
  • ahh...yes I agree with you, and this is what I'm doing right now. But, suppose I have 50 documents in the given radius, and I'm using limit of 10 or 20. If, **within_spherical_circle** is not giving sorted results, its hard to make sure I got the nearest 10 or 20 only. Otherwise I have to make request for bigger chunk of data (50 or 100). sort them and the use limit on resultant array to get the desired result (approximately). Any guess? – r3bo0t Mar 20 '14 at 05:22
  • Also with solution, for some specific circles I have more then 100k of documents in density. So, this is not feasible in this particular case to do a distance calculation on complete result set. – r3bo0t Mar 24 '14 at 02:00
  • i understand is a lot of data, but you cann't apply the limit after the sort? you can use take for this `@array_of_items_in_the_circle.sort_by(&:distance).take(20)` – Alexis Mar 25 '14 at 06:24