Msantamaria
Msantamaria

Reputation: 73

struggling with geospatial queries on mongo

I have been struggling for a few days trying to get queries to work. At the moment my model looks like this:

class Geojson
  include Mongoid::Document

  field :type, type: String, default: 'Point'
  field :coordinates, type: Array

  index({coordinates: "2dsphere"}, { bits: 12}) 
end

The following query returns nil:

Geojson.find(:coordinates => {"$nearSphere" => [-70.1197340629727, 4.67071244438]})

These are the current instances in my database:

[#<Geojson _id: 61b7b21a9eb0c9ef0aa5626d, type: "Point", coordinates: [-74.13041168951031, 4.6638117]>,
#<Geojson _id: 61b7b2619eb0c9ef0aa5626e, type: "Point", coordinates: [-74.1213041168951, 4.5638117]>] 

I am able to query similar cases on mongosh with no issues, however I am not sure where the mistake is when doing it directly on rails.

Upvotes: 1

Views: 120

Answers (1)

Msantamaria
Msantamaria

Reputation: 73

I finally managed to make it work the following way: (for a 2d sphere index)

Geojson.where(:coordinates => {"$nearSphere" => [long, lat]}).to_a

Where longitude and latitude are the parameters received.

Upvotes: 1

Related Questions