地理空间搜索
MongoDB 提供了多种索引和查询机制来处理地理空间信息。本节演示了如何创建和使用地理空间索引 使用 Ruby 驱动程序。
本页上的示例使用一个名为restaurants
的样本集合,位于 test
数据库中。一个样本数据集 可供下载。
以下是在 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": 1299715200000 }, "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[:restaurants].indexes.create_one( { 'address.coord' => '2dsphere' })
索引创建完成后,您可以使用多个操作符对其进行查询,包括 $near、$geoWithin 和 $geoIntersects 操作符。以下示例使用 $near
操作符查找所有在给定坐标500米范围内的餐厅。
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test') collection = client[:restaurants] collection.find( { 'address.coord' => { "$near" => { "$geometry" => { "type" => "Point", "coordinates" => [ -73.96, 40.78 ] }, "$maxDistance" => 500 } } } ).each do |doc| #=> Yields a BSON::Document. end
要查找所有位于给定多边形范围内的文档,请使用 $geoWithin
操作符
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test') collection = client[:restaurants] collection.find( { "address.coord" => { "$geoWithin" => { "$geometry" => { "type" => "Polygon" , "coordinates" => [ [ [ -73, 40 ], [ -74, 41 ], [ -72, 39 ], [ -73, 40 ] ] ] } } } } ).each do |doc| #=> Yields a BSON::Document. end