如何使用Mongoid执行$ geoIntersects查询?

chr*_*man 5 geospatial sinatra mongodb mongoid

我正在使用Sinatra和mongoid驱动程序,现在我正在尝试在mongoid中执行此查询,实际上我有一个名为' geometry ' 的地理空间(Polygon)字段:

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

实际上这个查询在mongodb shell中有效.

但是,我想找到与给定点(多边形点)与mongoid或其他红宝石驱动器相交的状态.

任何帮助将不胜感激.

谢谢.

Hil*_*lde 5

我最近在搜索这个,过了一会儿我发现了以下内容.也许别人会对此有用..

$ 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 ]])
Run Code Online (Sandbox Code Playgroud)

并提交: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 ]])
Run Code Online (Sandbox Code Playgroud)

在我的项目中我有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
Run Code Online (Sandbox Code Playgroud)

和模型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
Run Code Online (Sandbox Code Playgroud)

此代码返回内部具有此点的所有多边形.

可能有更优雅的方式来做到这一点.如果是这样我想听听:)


小智 3

我一直在考虑做同样的事情。据我所知,Mongoid 尚不支持此功能,而且我不知道实现它的时间范围。

同时,您可以使用 Mongoid/Moped 驱动程序来运行查询,但您不会获得 Mongoid 提供的任何对象映射功能 - 您只会获得数组/哈希值。示例语法如下:

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

这实际上返回一个带有键“_id”和 _id 字段值的哈希数组,但您可以根据需要进行配置。