我是 MongoDB 的新手,使用 java 驱动程序.. 我尝试从一个集合中查询多边形并在另一个集合中查询匹配点。
我实际上拥有的是:
//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();
我不知道回答他自己的问题是否正确,但也许对其他人有帮助..
关于java - MongoDB 查询多边形内的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61441452/