Alex
Alex

Reputation: 38529

Using geoNear with Rails / Mongoid

I'm having problems querying Geospatial indexes with MongoDB / Rails. I'm using this gem - https://github.com/kristianmandrup/mongoid_geospatial

Here's my fairly basic model:

class Company
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Geospatial

  field :name, type: String

  field :location, type: Array, spatial: true

  spatial_index :location

  validates :location, location: true
end

Then, in my controller, I have this

    #@vendors = Vendor.where(:location.near => {:point => [-2.1294761000000335,57.0507625], :max => 5})

However, this isn't returning expected results (ie- it's returning things from all over the place, not just near that particular lon / lat)

Also, how would I go about doing a geoNear with this?
So that I can get back the distances from central point for each result?

Note After writing this question, I've seen the gem has been updated, but I'm not sure if there's a better alternative..?

Upvotes: 1

Views: 2479

Answers (1)

kynan
kynan

Reputation: 13643

You don't need the mongoid_geospatial gem to do a geoNear query: mongoid already supports it (in version 3 at least).

Change your model to:

class Company
  include Mongoid::Document
  include Mongoid::Timestamps

  field :name, type: String

  field :location, type: Array

  index({location: "2d"})

  validates :location, location: true
end

And run your query as:

@vendors = Vendor.geo_near([-2.1294761000000335,57.0507625]).max_distance(5)

Upvotes: 5

Related Questions