To support geospatial queries, MongoDB provides various geospatial indexes as well as geospatial query operators.
The example below requires a
restaurantscollection in the
testdatabase. To create and populate the collection, follow the directions in github.
Include 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
This guide uses the
Observableimplicits as covered in the Quick Start Primer.
Connect to a MongoDB Deployment
Connect to a MongoDB deployment and declare and define a
For example, include the following code to connect to a standalone MongoDB deployment running on localhost on port
27017 and define
database to refer to the
val mongoClient: MongoClient = MongoClient() val database: MongoDatabase = mongoClient.getDatabase("test")
For additional information on connecting to MongoDB, see Connect to MongoDB.
The following example creates a
2dsphere index on the
"contact.location" field for the
val collection = database.getCollection("restaurants") 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 queries filters, the Scala driver provides the
Filters class and the
The following example returns documents that are at least 1000 meters from and at most 5000 meters from the specified GeoJSON point
org.mongodb.scala.model.geojson.Point, 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()