【问题标题】:MongoDB with Mongoid in Rails - Geospatial Indexing在 Rails 中使用 Mongoid 的 MongoDB - 地理空间索引
【发布时间】:2011-12-03 20:57:32
【问题描述】:

MongoDB 有一个非常好的Geospatial Indexing 功能。如何在带有 Mongoid 的 Rails 中使用它?

【问题讨论】:

    标签: ruby-on-rails ruby mongodb geolocation mongoid


    【解决方案1】:

    你可以在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]}})
    

    这将帮助您找到给定边界框中的项目。

    【讨论】:

    • 当我尝试使用 $near 命令(使用 maxDistance)时,它返回一个错误:地理值必须是数字:{ $maxDistance: 0.001799856011519079, $near: [ 80.249, 13.060422 ] } 有什么想法吗?它只适用于“$near”,但是当我添加“$maxDistance”时,它会窒息。
    • @Vasily,我不确定.. 带有 $maxdistance 的 $near 查询与您指定的值完美配合。 Item.where(:loc => {"$near" => [ 80.249, 13.060422 ] , '$maxDistance' => 0.001799856011519079})。它工作正常..也许你可以告诉我你正在尝试的查询?到时候再看
    • 我在使用 maxDistance 时遇到了同样的错误。红宝石 1.8。你们找到解决办法了吗?
    【解决方案2】:

    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 })。干杯。
    【解决方案3】:

    所有这些答案对于最新版本的 MongoDB 来说都是过时的,并且会抛出一些 uninitialized constant Mongo::GEO2D

    对于 mongoid 4/5,如果您需要玩 2D 对象或坐标,我建议您查看mongoid-geospatial gem

    【讨论】:

      猜你喜欢
      • 2016-02-12
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      相关资源
      最近更新 更多