|
| 1 | +.. _scala-geospatial: |
| 2 | + |
| 3 | +================= |
| 4 | +Geospatial Search |
| 5 | +================= |
| 6 | + |
| 7 | +.. facet:: |
| 8 | + :name: genre |
| 9 | + :values: reference |
| 10 | + |
| 11 | +.. meta:: |
| 12 | + :keywords: code example, search coordinates, location |
| 13 | + |
| 14 | +.. contents:: On this page |
| 15 | + :local: |
| 16 | + :backlinks: none |
| 17 | + :depth: 2 |
| 18 | + :class: singlecol |
| 19 | + |
| 20 | +To support geospatial queries, MongoDB provides geospatial |
| 21 | +indexes and geospatial query operators. |
| 22 | + |
| 23 | +To learn more about performing geospatial queries, see |
| 24 | +:manual:`Geospatial Queries </geospatial-queries/>` in the |
| 25 | +Server manual. |
| 26 | + |
| 27 | +Prerequisites |
| 28 | +------------- |
| 29 | + |
| 30 | +.. include:: /includes/prereq-restaurants.rst |
| 31 | + |
| 32 | +.. code-block:: scala |
| 33 | + |
| 34 | + import org.mongodb.scala._ |
| 35 | + import org.mongodb.scala.model.geojson._ |
| 36 | + import org.mongodb.scala.model.Indexes |
| 37 | + import org.mongodb.scala.model.Filters |
| 38 | + |
| 39 | +.. include:: /includes/obs-note.rst |
| 40 | + |
| 41 | +Connect to a MongoDB Deployment |
| 42 | +------------------------------- |
| 43 | + |
| 44 | +.. include:: /includes/connect-section.rst |
| 45 | + |
| 46 | +Create a 2dsphere Index |
| 47 | +----------------------- |
| 48 | + |
| 49 | +To create a ``2dsphere`` index, use the ``Indexes.geo2dsphere()`` |
| 50 | +helper to create a specification for the ``2dsphere`` index. Pass the |
| 51 | +specification to the ``MongoCollection.createIndex()`` method to create |
| 52 | +the index. |
| 53 | + |
| 54 | +The following example creates a ``2dsphere`` index on the |
| 55 | +``"contact.location"`` field in the collection: |
| 56 | + |
| 57 | +.. code-block:: scala |
| 58 | + |
| 59 | + collection.createIndex(Indexes.geo2dsphere("contact.location")).printResults() |
| 60 | + |
| 61 | +Query for Locations Near a GeoJSON Point |
| 62 | +---------------------------------------- |
| 63 | + |
| 64 | +MongoDB provides various geospatial query operators. To facilitate |
| 65 | +the creation of geospatial query filters, the driver provides |
| 66 | +the ``Filters`` class and the ``com.mongodb.client.model.geojson`` |
| 67 | +package. |
| 68 | + |
| 69 | +The following example returns documents that are at least ``1000.0`` meters |
| 70 | +and at most ``5000.0`` meters from the specified GeoJSON ``Point`` instance, |
| 71 | +automatically sorted from nearest to farthest: |
| 72 | + |
| 73 | +.. code-block:: scala |
| 74 | + |
| 75 | + val refPoint = Point(Position(-73.9667, 40.78)) |
| 76 | + collection.find(Filters.near("contact.location", refPoint, 5000.0, 1000.0)).printResults() |
0 commit comments