MongoDB 在嵌套键值中查询并在值列表中进行比较

MongoDB query in nested key value and compare inside value list

我的数据库看起来像

{
  "_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 驱动程序进行地理空间搜索非常好。