Skip to content

Instantly share code, notes, and snippets.

@tgrall
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgrall/04e1e1a878a5b3db349d to your computer and use it in GitHub Desktop.
Save tgrall/04e1e1a878a5b3db349d to your computer and use it in GitHub Desktop.
Sample Java GeoQuery
import com.mongodb.*;
/**
* Created by tgrall on 8/27/14.
*/
public class TestApp {
public static void main(String[] args) throws Exception {
MongoClient client = new MongoClient();
DB db = client.getDB( "geo" );
DBCollection collection = db.getCollection("states");
DBCollection airports = db.getCollection("airports");
// find the "geojson" polygon of the California state
DBObject query = QueryBuilder.start()
.put("code").is("CA")
.get();
DBObject state = collection.findOne(query);
DBObject polygon = (DBObject)state.get("loc");
//System.out.println(polygon);
// Find all the airports that intersect with this
// use a direct DBObject since the Query Builder does not suppor to Geospatial feature yet
// see https://jira.mongodb.org/browse/JAVA-1195
DBObject geometryClause = BasicDBObjectBuilder.start()
.add("$geometry", polygon)
.get();
DBObject geoQuery = BasicDBObjectBuilder.start()
.push("loc")
.add( "$geoIntersects", geometryClause )
.get();
Cursor cursor = airports.find( geoQuery );
while( cursor.hasNext() ){
DBObject airport = cursor.next();
System.out.println( airport.get("code") +" "+ airport.get("name") );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment