ruby-on-rails – MongoDB与Mongoid在Rails – 地理空间索引
发布时间:2020-12-16 20:27:18 所属栏目:百科 来源:网络整理
导读:MongoDB有一个非常好的 Geospatial Indexing功能.如何在Mongoid的Rails中使用它? 解决方法 您可以在mongoid中定义这样的地理索引 class Item include Mongoid::Document field :loc,:type = Array index( [ [:loc,Mongo::GEO2D] ],background: true )end 和
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(一度约为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]}}) 这将帮助您找到给定边框内的项目. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |