docs/reference/geospatial-search.txt
*****************
Geospatial Search
*****************
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
MongoDB offers a number of indexes and query mechanisms to handle
geospatial information. This section demonstrates how to create
and use
:manual:`geospatial indexes</applications/geospatial-indexes/>`
with the Ruby driver.
The examples on this page use a sample collection called
``restaurants`` in the ``test`` database.
A `sample dataset <https://www.mongodb.com/docs/getting-started/shell/import-data/>`_
is available for download.
The following is a sample document in the ``restaurants``
collection:
.. code-block:: javascript
{
"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"
}
The following example creates a ``2dsphere`` index on the
``address.coord`` field:
.. code-block:: ruby
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test' )
client[:restaurants].indexes.create_one( { 'address.coord' => '2dsphere' })
Once the index is created, you can use several operators to query
against it, including the
:manual:`$near</reference/operator/query/near/>`,
:manual:`$geoWithin</reference/operator/query/geoWithin/>`, and
:manual:`$geoIntersects</reference/operator/query/geoIntersects/>`
operators. The following example uses the ``$near`` operator to find
all restaurants within 500 meters of the given coordinates.
.. code-block:: ruby
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
To find all documents with a location within the
perimeter of a given polygon, use the ``$geoWithin``
operator:
.. code-block:: ruby
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