Ruby操作MongoDB(进阶十一)--空间信息搜索Geospatial Search

时间:2021-01-09 00:52:48

  上篇博文中介绍了,文本搜索的相应功能。

  MongoDB数据库为空间信息的处理操作提供了一系列的索引和查询机制。本篇博文将在Ruby驱动上展示如何创建和适用空间索引。下面的实例使用了test数据库中的一个叫做restaurants的简单集合。

 下面是restaurants集合

{
 "address":{
       "building":"1007",
       "coord":[-73.856077,40.848447],
       "street":"Morris Park Ave",
       "zipcode":"10462"
 },
 "borough":"Bronx",
 "cuisine":"Bakery",
 "grades":{
     {"date":{"$date":1393804800000},"grade":"A","score":2},
     {"date":{"$date":1299152000000},"grade":"B","score":14},
 },
 "name":"Morris Park Bake Shop",
 "restaurant_id":"30075445"
}

  下面的代码在address.coord字段上创建了一个2dsphere的索引。

client=Mongo::Client.new(['127.0.0.1:27017'],:database=>'test')client[:restaurant].indexes.create_one({'address.coord'=>'2dsphere'})

  一旦创建了这个索引,就可以在上面使用诸如$near,$geoWithin,$geoIntersects操作符。下面的例子中展示了如何通$near操作符在集合中找到所有距离坐标距离不超过500米的饭店

client=Mongo::Client.new(['127.0.0.1:27017'],:database=>'test')collection=client[:restaurants]collection.find(         {'address.coord'=>             {                "$near"=>{                      "$geometry"=>{                         {"$type"=>"Point","coordinates"=>[-73.96,40.78]},                         "$maxDistance"=>500                      }                }             }        }).each do |doc|        p docend

   为了找出所有所有位置信息在给定的多边形边界范围内的文档信息,使用$geoWithIn操作符。

client=Mongo::Client.new(['mongodb://127.0.0.1:27017/test'])collection=client[:restaurants]collection.find(               {                  "address.coord"=>{                     {"$geoWithIn"=>                        { "$geometry"=>                           {"type"=>"Ploygon",                           "corrdinates"=>[[[-73,48],[-74,41],[-72,39],[-73,40]]]                           }                         }                     }                  }               }               ).each do |doc|               p doc end

MongoDB的空间操作到此结束

本文出自 “techFuture” 博客,谢绝转载!