0

How to write this mongodb shell query with using java?

query : db.building_feature.find({geometry : {$geoIntersects :{$geometry :{type : "Polygon", coordinates :[[[37.59777,55.73216],[37.59805,55.77615],[37.68710,55.77643],[37.68517,55.73290],[37.59777,55.73216]]]}}}})

My collection GeoSpatialIndex is "2dsphere".

My version which is not working :

DBCollection testCollection = db.getCollection("building_feature");  
final LinkedList<double[]> geo = new LinkedList<>();
geo.addLast(new double[]{37.59777, 55.73216});
geo.addLast(new double[]{37.59805, 55.77615});
geo.addLast(new double[]{37.68710, 55.77643});
geo.addLast(new double[]{37.68517, 55.73290});

final BasicDBObject query
    = new BasicDBObject("geometry", new BasicDBObject("$within", new BasicDBObject("$geometry", geo)));
System.out.println("Result Count : " + testCollection.find(query).count());

Thanks.

1 Answer 1

1

You should write exactly the same query in Java:

BasicDBObject polygon = new BasicDBObject("type", "Polygon");
polygon.put("coordinates", <myArray>);

BasicDBObject query = new BasicDBObject(
    "geometry", new BasicDBObject(
        "$geoIntersects", new BasicDBObject(
            "$geometry", polygon
        )
    )
);

<myArray> being your triple-nested double[][][] geoJSON polygon coordinates array.

Btw, it could be more clear to read with a JSON string and then JSON.parse.

And I think $whithin operator does not exist in MongoDB...

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, can you give example "GeoJSONPolygonBasicDBObject" ?
Well, this is basic Java, and I think it is out of the purpose of the question, which concerns MongoDB API for Java. You don't want me to write all your code, I'm sure that Google will tell you how to create arrays in Java ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.