gpt4 book ai didi

java - MongoDB查询嵌套键值并比较内部值列表

转载 作者:太空宇宙 更新时间:2023-11-04 10:40:46 25 4
gpt4 key购买 nike

我的数据库看起来像

{
"_id" : ObjectId("5a8351093cf24e144d8fef24"),
"__type" : "TrafficIncident:http://schemas.microsoft.com/search/local/ws/rest/v1",
"point" : {
"type" : "Point",
"coordinates" : [
37.410883,
-95.71027
]
},
...
}
{
"_id" : ObjectId("5a8351093cf24e144d8fef25"),
"__type" : "TrafficIncident:http://schemas.microsoft.com/search/local/ws/rest/v2",
"point" : {
"type" : "Point",
"coordinates" : [
40.2346,
-100.826167
]
},
...
}

如果我有一个坐标对作为中心位置,比如[38, -98],并且我想检索坐标范围为[38 +- 2, -98 +- 2]的所有记录,如何为文档过滤器编写java代码?

到目前为止,我所做的是检索特定位置而不是范围内的位置。

Document query = new Document("point.coordinates", Arrays.asList(40.2346, -100.826167));
javamongo.collection.find(query).limit(javamongo.numLimit).forEach(printBlock);

最佳答案

您需要使用 MongoDB 的 Geospatial Query系统为此。

我假设您正在使用 Mongo's official Java Driver 。首先,您需要在 point.coordinates 字段上创建一个 2dsphere 索引。您可以在 Java 中执行此操作:

collection.createIndex(Indexes.geo2dsphere("point.coordinates"));

然后您可以通过以下方式查询您所在位置范围内的所有文档:

Point refPoint = new Point(new Position(38, -98));
collection.find(Filters.near("point.coordinates", refPoint, 2, 2)).forEach(printBlock);

MongoDB's tutorial使用他们的 Java 驱动程序进行地理空间搜索非常好。

关于java - MongoDB查询嵌套键值并比较内部值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48995444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com