Search code examples
mongodbmongodb-querymongodb-javanosql

mongodb shell query with java


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.


Solution

  • 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...