javamongodbmongo-java-driverrestheart

MongoDB query Points within Polygons


i am new to MongoDB with java driver.. i try to query polygons from one collection and match points in another collection.

what i actually have is:

//This is collection 1.. here i get my polygon definition.. the name of the element is geometry
Document polyDocument = mongoClient.getDatabase("restheart").getCollection("polygons").find(eq("properties.ISO_A2", "AT")).first();

//This is collection2.. here are the points saved which i want to select if they are within polygon.. the name of the element is location
MongoCursor<Document> Cursor = mongoClient.getDatabase("restheart").getCollection("coll2").aggregate(
                Arrays.asList(
                    Aggregates.match(geoWithin("location", polyDocument.get("geometry")),  <--- here is my problem, whats the correct syntax?
                    Aggregates.group("$hashtag", Accumulators.sum("Count", 1)),
                )
            ).iterator();

i googled now a lot but coulndt find a good example how to query this with javadriver

Sample of Collection 1:

{
    "_id" : ObjectId("5e95d56e49ebb0e6b45a34c4"),
    "type" : "Feature",
    "geometry" : {
        "type" : "Polygon",
        "coordinates" : [ 
            [ 
                [ ... , ... ]
            ]
        ]
    },
    "properties": { "ISO_A2": "AT" }
}

Sample of Collection 2:

{
    "_id" : ObjectId("5e90bf7b49ebb0e6b459a00f"),
    "hashtag" : "stayhome",
    "timestamp" : ISODate("2020-04-10T18:48:25.876Z"),
    "location" : {
        "type" : "Point",
        "coordinates" : [ 
            14.421425, 
            40.26084
        ]
    },
}

Solution

  • well, after some try and error i found a solution.. i dont know if its the smartest, but its working :)

    //This is collection 1.. here i get my polygon definition.. the name of the element is geometry
    Document polyDocument = mongoClient.getDatabase("restheart").getCollection("polygons").find(eq("properties.ISO_A2", "AT")).first();
    
    Document geoDocument = polyDocument.get("geometry", Document.class);
    String geoType = geoDocument.getString("type");
    List geoCoord = geoDocument.get("coordinates", List.class);
    BasicDBObject geometry = new BasicDBObject("type",geoType).append( "coordinates",geoCoord);
    
    //This is collection2.. here are the points saved which i want to select if they are within polygon.. the name of the element is location
    MongoCursor<Document> Cursor = mongoClient.getDatabase("restheart").getCollection("coll2").aggregate(
                    Arrays.asList(
                        Aggregates.match(geoWithin("location", geometry) ),
                        Aggregates.group("$hashtag", Accumulators.sum("Count", 1)),
                    )
                ).iterator();
    

    i dont know if its correct to answer his own question, but maybe it helps someone other..