Geospatial Search
On this page
To support geospatial queries, MongoDB provides geospatial indexes and geospatial query operators.
To learn more about performing geospatial queries, see Geospatial Queries in the Server manual.
Prerequisites
You must set up the following components to run the code examples in this guide:
A
test.restaurants
collection populated with documents from therestaurants.json
file in the documentation assets GitHub.The following import statements:
import org.mongodb.scala._ import org.mongodb.scala.model.geojson._ import org.mongodb.scala.model.Indexes import org.mongodb.scala.model.Filters
Note
This guide uses the Observable
implicits as covered in the
Quick Start Primer.
Connect to a MongoDB Deployment
First, connect to a MongoDB deployment, then declare and define
MongoDatabase
and MongoCollection
instances.
The following code connects to a standalone
MongoDB deployment running on localhost
on port 27017
. Then, it
defines the database
variable to refer to the test
database and
the collection
variable to refer to the restaurants
collection:
val mongoClient: MongoClient = MongoClient() val database: MongoDatabase = mongoClient.getDatabase("test") val collection: MongoCollection[Document] = database.getCollection("restaurants")
To learn more about connecting to MongoDB deployments, see the Connect to MongoDB tutorial.
Create a 2dsphere Index
To create a 2dsphere
index, use the Indexes.geo2dsphere()
helper to create a specification for the 2dsphere
index. Pass the
specification to the MongoCollection.createIndex()
method to create
the index.
The following example creates a 2dsphere
index on the
"contact.location"
field in the collection:
collection.createIndex(Indexes.geo2dsphere("contact.location")).printResults()
Query for Locations Near a GeoJSON Point
MongoDB provides various geospatial query operators. To facilitate
the creation of geospatial query filters, the driver provides
the Filters
class and the com.mongodb.client.model.geojson
package.
The following example returns documents that are at least 1000.0
meters
and at most 5000.0
meters from the specified GeoJSON Point
instance,
automatically sorted from nearest to farthest:
val refPoint = Point(Position(-73.9667, 40.78)) collection.find(Filters.near("contact.location", refPoint, 5000.0, 1000.0)).printResults()