【发布时间】:2011-12-03 20:57:32
【问题描述】:
MongoDB 有一个非常好的Geospatial Indexing 功能。如何在带有 Mongoid 的 Rails 中使用它?
【问题讨论】:
标签: ruby-on-rails ruby mongodb geolocation mongoid
MongoDB 有一个非常好的Geospatial Indexing 功能。如何在带有 Mongoid 的 Rails 中使用它?
【问题讨论】:
标签: ruby-on-rails ruby mongodb geolocation mongoid
你可以在mongoid中定义这样的地理索引
class Item
include Mongoid::Document
field :loc, :type => Array
index(
[
[:loc, Mongo::GEO2D]
], background: true
)
end
对于查询
$near 命令(不带 maxDistance)
location = [80.24958300000003, 13.060422]
items = Item.where(:loc => {"$near" => location})
$near 命令(带 maxDistance)
distance = 10 #km
location = [80.24958300000003, 13.060422]
items = Item.where(:loc => {"$near" => location , '$maxDistance' => distance.fdiv(111.12)})
使用 km 时将距离转换为 111.12(1 度约为 111.12 公里),或使用度数保持距离不变
$centerSphere / $nearSphere 查询
location = [80.24958300000003, 13.060422]
items = Item.where(:loc => {"$within" => {"$centerSphere" => [location, (distance.fdiv(6371) )]}})
这将找到 10 公里半径内的项目。在这里我们需要转换距离/6371(地球半径)以使其与km一起使用。
$box(边界框查询)
first_loc = [80.24958300000003, 13.060422]
second_loc = [81.24958300000003, 12.060422]
items = Item.where(:loc => {"$within" => {"$box" => [first_loc, second_loc]}})
这将帮助您找到给定边界框中的项目。
【讨论】:
Item.where(:loc => {"$near" => [ 80.249, 13.060422 ] , '$maxDistance' => 0.001799856011519079})。它工作正常..也许你可以告诉我你正在尝试的查询?到时候再看
RameshVel 的回答很棒。
作为更新,在 Mongoid 3.0.4 中,我必须按如下方式定义索引以使其与 rake db:mongoid:create_indexes 一起使用:
index(
{ loc: Mongo::GEO2D },
{ background: true }
)
【讨论】:
Mongoid 3.0.0,文档指示以下格式index({ loc: "2d" }, { min: -200, max: 200 })。干杯。
所有这些答案对于最新版本的 MongoDB 来说都是过时的,并且会抛出一些 uninitialized constant Mongo::GEO2D
对于 mongoid 4/5,如果您需要玩 2D 对象或坐标,我建议您查看mongoid-geospatial gem。
【讨论】: