Implementing geospatial queries in java

78 views
Skip to first unread message

pinaki ghosh

unread,
Feb 19, 2015, 10:55:45 PM2/19/15
to mongod...@googlegroups.com
I want to replicate the following query in Java
db.airports.find(
{
  loc
: {
    $near
: {
      $geometry
: {
        type
: "Point" ,
        coordinates
: [-73.965355,40.782865]
     
},
      $maxDistance
: 20000
   
}
 
},
  type
: "International"
},
{
  name
: 1,
  code
: 1,
  _id
: 0
}
);



I tried
BasicDBList geoCoord = new BasicDBList();
geoCoord
.add(lng);
geoCoord
.add(lat);
BasicDBObject geometry = new BasicDBObject("type", "Point");
geometry
.append("coordinates", geoCoord);
BasicDBObject near = new BasicDBObject("$geometry", geometry);
BasicDBObject query = new BasicDBObject();
query
.append("$maxDistance", distance);
query
.append("$nearSphere", near);
 but it throws me this error
com.mongodb.CommandFailureException: { "serverUsed" : "127.0.0.1:27017" , "errmsg" : "exception: unknown top level operator: $maxDistance" , "code" : 2 , "ok" : 0.0}

I have indexed the location column.

Will Berkeley

unread,
Feb 20, 2015, 2:54:18 AM2/20/15
to mongod...@googlegroups.com
The error indicates you constructed the query inappropriately, with $maxDistance out of place. If I translate query into mongo shell BSON syntax, I believe it's

{
   
"$maxDistance" : distance,    // :(
   
"$nearSphere" : {
       
"$geometry" : {
           
"type" : "Point",
           
"coordinates" : [lng, lat]
       
}
   
}
}

The problem is caused by $maxDistance being at the top level rather than inside $near/$nearSphere. I believe the correct code to construct the geo query is

BasicDBList geoCoord = new BasicDBList();
geoCoord
.add(lng);
geoCoord
.add(lat);
BasicDBObject geometry = new BasicDBObject("type", "Point");
geometry
.append("coordinates", geoCoord);
BasicDBObject near = new BasicDBObject("$geometry", geometry);
BasicDBObject query = new BasicDBObject();

near
.append("$maxDistance", distance);        // CHANGED
query
.append("$nearSphere", near);

-Will
Reply all
Reply to author
Forward
0 new messages