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.restaurantscollection populated with documents from therestaurants.jsonfile in the documentation assets GitHub.The following import statements:
import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoCollection; import com.mongodb.reactivestreams.client.MongoDatabase; import com.mongodb.client.model.geojson.*; import com.mongodb.client.model.Indexes; import com.mongodb.client.model.Filters; import org.bson.Document;
Important
This guide uses custom Subscriber implementations, which are
described in the Sample Custom Subscriber Implementations guide.
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:
MongoClient mongoClient = MongoClients.create(); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("restaurants");
To learn more about connecting to MongoDB deployments, see the Connect to MongoDB tutorial.
Create the 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 restaurants collection:
MongoCollection<Document> collection = database.getCollection("restaurants"); collection.createIndex(Indexes.geo2dsphere("contact.location")) .subscribe(new PrintSubscriber<String>());
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 meters
and at most 5000 meters from the specified GeoJSON Point instance,
sorted from nearest to farthest:
Point refPoint = new Point(new Position(-73.9667, 40.78)); collection.find(Filters.near("contact.location", refPoint, 5000.0, 1000.0)) .subscribe(new PrintDocumentSubscriber());