【问题标题】:MongoDB query in nested key value and compare inside value listMongoDB查询嵌套键值并比较内部值列表
【发布时间】:2018-02-26 19:09:03
【问题描述】:

我的数据库看起来像

{
  "_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);

【问题讨论】:

    标签: java mongodb filter documentfilter


    【解决方案1】:

    您需要为此使用 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 驱动程序进行地理空间搜索非常好。

    【讨论】:

    • 谢谢,我选择了geoWithin,效果很好。另一个问题是MongoDB默认使用(longitude, latitude)作为查询,而存储在我的数据库中的数据是[纬度,经度]。因此它有错误"Can't extract geo keys"。无论如何要修复查询而不是更改或预处理数据库中的数据。
    • 不幸的是,我不这么认为,而且看起来他们没有改变这一点的计划 - jira.mongodb.org/browse/SERVER-27548
    • 嗯,顺便说一句,这很有趣。感谢您的帮助。
    猜你喜欢
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多