地理空间Atlas Search
MongoDB 提供许多索引和查询机制来处理地理空间信息。 本部分演示如何通过 Ruby 驱动程序创建和使用地理空间索引。
本页上的示例使用test
数据库中名为 restaurants
的示例集合。 样本数据集可供下载。
以下是restaurants
collection中的文档:
{ "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