MongoDB有一个很好的Geospatial Indexing特征。如何在带有 Mongoid 的 Rails 中使用它?
最佳答案
你可以在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]}})
这将帮助您找到给定边界框中的项目。
关于ruby-on-rails - 在 Rails 中使用 Mongoid 的 MongoDB - 地理空间索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7702244/