How to execute a $ geoIntersects query with Mongoid?

I use the Sinatra and mongoid driver , now I'm trying to execute this request in mongoid, in fact I have a geospatial (polygonal) field called " geometry ":

db.states.find({
    geometry: {
        $geoIntersects: {
            $geometry: {
                type: "Point",
                coordinates: [-99.176524, 18.929204]
            }
        }
    }
})

Actually this request works in mongodb shell.

However, I want to find states that intersect with a given point (Point-in-polygon) with a mango or, possibly, another ruby ​​driver.

Any help would be greatly appreciated.

Thank.

+5
source share
3 answers

, . , , Mongoid, , .

Mongoid/Moped , , Mongoid, /. :

ids = Mongoid.default_session["states"].find( geometry:
    { "$geoIntersects" =>
        { "$geometry" =>
            { type: "Point", coordinates: [-99.176524, 18.929204] }
        }
    }
).select( id: 1 )

"_id" _id, .

+3

, . , - .

$geoIntersects mongoid 4.0.0.beta1, . : https://github.com/mongoid/origin/blob/master/CHANGELOG.md#new-features-1

query.geo_spacial(:location.intersects_line => [[ 1, 10 ], [ 2, 10 ]])
query.geo_spacial(:location.intersects_point => [[ 1, 10 ]])
query.geo_spacial(:location.intersects_polygon => [[ 1, 10 ], [ 2, 10 ], [ 1, 10 ]])
query.geo_spacial(:location.within_polygon => [[ 1, 10 ], [ 2, 10 ], [ 1, 10 ]])

: https://github.com/mongoid/origin/commit/30938fad644f17fe38f62cf90571b78783b900d8

 # Add a $geoIntersects selection. Symbol operators must be used as shown in
 # the examples to expand the criteria.
 #
 # @note The only valid geometry shapes for a $geoIntersects are: :line,
 #   :point, and :polygon.
 # ...
 # @example Add a geo intersect criterion for a point.
 #   query.geo_intersects(:location.point => [[ 1, 10 ]])

mongoid (4.0.0.beta1) origin (2.1.0) Polygon

class Polygon
  include Mongoid::Document
  # some fields 

  embeds_many :loc

  # coordinates is an array of two points: [10, 12]
  def find_polygons_with_point(coordinates)
    # This is where the magic happens!
    Polygon.all.geo_spacial(:loc.intersects_point => coordinates)
  end

end

Loc

class Loc
  field :type, type: String #Need to be set to 'Polygon' when creating a new location.
  field :coordinates, type: Array
  # For some reason the array has to be in the format
  # [ [ [1,1], [2,3], [5,3], [1,1] ] ]
  # And the first coordinate needs to be the same as the last
  # to close the polygon

  embedded_in :polygon

  index({ coordinates: "2d" }, { min: -200, max: 200 }) #may not need min/max
end

, .

. , :)

+5

Mongoid 4.0 $geoIntersects, . . ( ):

/usr/local/lib/ruby/gems/1.9.1/gems/origin-1.1.0/lib/origin/selectable.rb

:

def geo_intersects(criterion = nil)
   __override__(criterion, "$geoIntersects")
end
key :geo_intersects, :override, "$geoIntersects"

:

Houses.where(:color => "red").geo_intersects(:loc => {"$geometry" => {:type => "Polygon", :coordinates => [[[1,2],[2,3][1,2]]]})
+1

All Articles