Docs 菜单

Docs 主页开发应用程序MongoDB 驱动程序Ruby MongoDB 驱动程序

地理空间搜索

MongoDB 提供许多索引和查询机制来处理地理空间信息。 本部分演示如何通过 Ruby 驱动程序创建和使用地理空间索引

本页上的示例使用数据库中名为restaurants test的collection。 示例数据集 可供下载。

以下是restaurantscollection中的文档:

{
"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
←  文本搜索(Text Search)查询缓存 →