ruby-on-rails - 在 Rails 中使用 Mongoid 的 MongoDB - 地理空间索引

标签 ruby-on-rails ruby mongodb geolocation mongoid

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/

相关文章:

node.js - 使用 mongoose 创建唯一的自动增量字段

node.js - 如何在 Node.js 和 Mongoose 中在一段时间后更新用户?

ruby-on-rails - View 中的 Rails Helpers - Rails 中未定义的局部变量或方法

ruby-on-rails - 如何构建任务 'generate_secret_token'

ruby-on-rails - Rails/Devise - 强制密码重置

ruby-on-rails - 多个 model.save's in 1 if condition with an unless

mongodb - meteor ,Mongo 查询查找每第 n 个文档

ruby-on-rails - 使用 Capybara,如何判断当前使用的驱动程序是否支持 JavaScript?

ruby-on-rails - 模型的日期时间字段在 heroku 上的存储方式与本地主机不同

ruby - 如何在 ruby​​ 中创建平面文件