MongoDB查询多边形内的点



我是使用java驱动程序的MongoDB新手。。我试着查询一个集合中的多边形和另一个集合的匹配点。

我实际拥有的是:

//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();

我现在在谷歌上搜索了很多,但可以找到一个很好的例子来使用javadriver查询

样本1:

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

样本2:

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

好吧,经过一番尝试和错误,我找到了解决方案。。我不知道它是否是最聪明的,但它有效:(

//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();

我不知道回答他自己的问题是否正确,但也许这对其他人有帮助。。

最新更新