简体   繁体   English

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

[英]MongoDB with Mongoid in Rails - Geospatial Indexing

MongoDB has a very nice Geospatial Indexing feature. MongoDB具有非常好的地理空间索引功能。 How can I use it in Rails with Mongoid? 我怎样才能在带有Mongoid的Rails中使用它?

You can define geo indexes like this in mongoid 您可以在mongoid中定义这样的地理索引

class Item
  include Mongoid::Document

  field :loc, :type => Array

  index(
      [
          [:loc, Mongo::GEO2D]             
      ], background: true

  )
end

And for queries 对于查询

$near command (without maxDistance) $ near命令(不带maxDistance)

 location = [80.24958300000003, 13.060422]
 items = Item.where(:loc => {"$near" => location})

$near command (with maxDistance) $ near命令(使用maxDistance)

 distance = 10 #km
 location = [80.24958300000003, 13.060422]
 items = Item.where(:loc => {"$near" => location , '$maxDistance' => distance.fdiv(111.12)})

Convert distance by 111.12 (one degree is approximately 111.12 kilometers) when using km, or leave distance as it is on using degree 使用km时,将距离转换为111.12(一度约为111.12公里),或者使用度数保持距离

$centerSphere / $nearSphere queries $ centerSphere / $ nearSphere查询

location = [80.24958300000003, 13.060422]
items = Item.where(:loc => {"$within" => {"$centerSphere" => [location, (distance.fdiv(6371) )]}})

This will find the items within the 10 km radius. 这将找到半径10公里范围内的物品。 Here we need to convert the distance/6371(earth radius) to get it work with km. 在这里,我们需要转换距离/ 6371(地球半径)以使其与km一起工作。

$box (bounding box queries) $ box (边界框查询)

 first_loc = [80.24958300000003, 13.060422]
 second_loc = [81.24958300000003, 12.060422]
 items = Item.where(:loc => {"$within" => {"$box" => [first_loc, second_loc]}})

This will help you to find the items within the given bounding box. 这将帮助您找到给定边界框内的项目。

RameshVel's answer is great. RameshVel的答案很棒。

As an update, in Mongoid 3.0.4, I had to define the index as follows to make it work with rake db:mongoid:create_indexes : 作为更新,在Mongoid 3.0.4中,我必须按如下方式定义索引以使其与rake db:mongoid:create_indexes

index(
  { loc: Mongo::GEO2D },
  { background: true }
)

All those answers are a outdated with newest versions of MongoDB and will throw some uninitialized constant Mongo::GEO2D 所有这些答案都是过时的最新版MongoDB,并会抛出一些uninitialized constant Mongo::GEO2D

For mongoid 4/5, I suggest you have look at the mongoid-geospatial gem if you need to play with 2D Objects or coordinates. 对于mongoid 4/5,如果您需要使用2D对象或坐标,我建议您查看mongoid-geospatial gem

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM