【问题标题】:MongoDB - Java | Use of $nearMongoDB - Java | $near 的使用
【发布时间】:2023-03-25 02:50:01
【问题描述】:

我将一些帖子保存在这样的 MongoDB 集合中:

{
    "_id": {
        "$oid": "56e7152edbaacc2ab1d34f20"
    },
    "title": "the title",
    "body": "the post",
    "loc": {
       "lat": 40.616856,
       "lng": 22.954689
    },
    "timestamp": "1457984814748",
    "username": "User",
    "fbID": "4324"
}

我想获取特定比例的帖子,比如说 2 公里。

我正在尝试查找 $near 的工作原理,但在 mongodb java 文档中找不到有关此函数的文档。如果有人知道我该怎么做或在哪里可以找到有关它的一些文档,将不胜感激。

这是我目前正在尝试的,texts 是来自 db 的集合:

        QueryBuilder query = new QueryBuilder();
        query.put("loc").near(22.9545545, 40.616479, 50);
        MongoCursor<Document> cursor2 = texts.find((BasicDBObject) query.get()).iterator();
        try {
            while (cursor2.hasNext()) {
                Document doc = cursor2.next();
                documents.add(doc);
            }
        } finally {
            cursor2.close();
        }

我也试过这个:

Double locationLongitude = new Double (22.9545545);
                Double locationLatitude = new Double (40.616479);
                BasicDBObject  locQuery = new BasicDBObject ();
                locQuery.put("loc", new Document("$near", new Double[]{locationLongitude, locationLatitude}));
MongoCursor<Document> cursor2 = texts.find(locQuery).iterator();
            try {
                while (cursor2.hasNext()) {
                    Document doc = cursor2.next();
                    documents.add(doc);
                }
            } finally {
                cursor2.close();
            }

更新

经过一番研究,我得出了这个结论:

我将我的 json 文档更改为:

{
    "_id": {
        "$oid": "56e9e7440296451112edd05d"
    },
    "title": "ρ",
    "body": "ρ",
    "lng": 22.954689,
    "lat": 40.616856,
    "loc": {
        "type": "Point",
        "coordinates": [
            22.954689,
            40.616856
        ]
    },
    "timestamp": "1458169668154",
    "username": "User",
    "fbID": "4324"
}

和我的java代码:

        collection.createIndex(new Document("loc", "2dsphere"));
        MongoCursor<Document> cursor = collection.find(near("loc", 22.9548626, 40.6159144, 100.0, 0.0)).iterator();

        try {
            while (cursor.hasNext()) {
                Document doc = cursor.next();
                documents.add(doc);
            }
        } finally {
            cursor.close();
        }

但仍然没有得到任何结果.. cursor 没有文档。 我也遇到这个错误

03-17 01:34:05.489 1786-1805/? W/System.err:com.mongodb.MongoQueryException:查询失败,错误代码 17007 和错误消息“无法执行查询:错误处理查询:ns=posts2.texts2 limit=0 skip=0 03-17 01:34:05.489 1786-1805/? W/System.err:树:GEONEAR 字段=loc maxdist=100 isNearSphere=0 03-17 01:34:05.489 1786-1805/? W/System.err:排序:{} 03-17 01:34:05.489 1786-1805/? W/System.err:项目:{} 03-17 01:34:05.489 1786-1805/? W/System.err:规划器返回错误:无法在服务器 ds011439.mlab.com:11439 上找到 $geoNear 查询的索引

【问题讨论】:

  • 你的 Java 代码在哪里?
  • @Saleem 我编辑了他的问题。感谢您的回复
  • 我的 json 也有变化。 “lng”和“lat”在“loc”中
  • 有关$near查询的基本信息,请参阅官方文档:docs.mongodb.org/manual/reference/operator/query/near。这不是关于 Java 驱动程序,而是关于一般的 mongo。尝试使用 mongo shell 并手动运行查询,直到您能够自己编写查询,然后切换到 Java 驱动程序。此外,您可以添加一些关于您的方法失败的原因/方式的信息。
  • 错误是不言自明的。 error: unable to find index for $geoNear query' on server ds011439.mlab.com:11439。不知道有什么难的

标签: java mongodb location


【解决方案1】:

我认为你的错误在这里
MongoCursor&lt;Document&gt; cursor = collection.find(near("loc", 22.9548626, 40.6159144, 100.0, 0.0)).iterator();

在您的 json 格式中,您的“loc”字段类型为:Point。 near 函数有另一个构造函数,它是 near(String field, Point point, Double max, Double min) 所以你应该使用Point 而不是22.9548626, 40.6159144,

你可以像这样创建一个点:

Position position = new Position(22.9548626,40.6159144);
Point point = new Point(position);

Here 是文档。

试一试。

【讨论】:

    【解决方案2】:

    我向您发布 shell 查询以帮助您了解 $near 的工作原理。

    首先,您需要在要运行位置感知查询的集合上创建2dsphere 索引。假设您的位置名称是loc

    db.loc.createIndex({loc:"2dsphere"})
    

    创建索引后,执行以下查询

    db.loc.find(
       {
         loc:
           { $near :
              {
                $geometry: { type: "Point",  coordinates: [ 40.617856, 22.954689 ] },
                $maxDistance: 2000
              }
           }
       }
    )
    

    它将搜索2000米(2Km)内的所有位置

    【讨论】:

    • 我更新了我的问题,你能帮我解决可能是什么错误吗?我想我越来越近了。感谢您迄今为止的努力:)
    • 要运行 GeoSpatial 查询,您需要先创建 2dsphere。这是一次性操作。
    • 我想我确实在collection.createIndex(new Document("loc", "2dsphere")); 中创建了一个二维球体索引,否?
    • 验证您的数据库是否已创建。打开 shell,连接到您的数据库并运行 db.col_what_ever.getIndexes()
    【解决方案3】:

    首先打开与数据库的 shell 连接并创建索引。

    db.Salons.createIndex({"loc":"2dsphere"});
    

    当您想要索引嵌套对象时:

    db.Salons.createIndex({"address.loc":"2dsphere"});
    

    这是查询 $near 的另一种方法

    //Imports
    import org.springframework.data.geo.Circle;
    import org.springframework.data.geo.Distance;
    import org.springframework.data.geo.Metrics;
    import org.springframework.data.geo.Point;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
        ....
    

    查找某个地点附近的沙龙

    Point point  = new Point(longitude, latitude);
    List<Salon> salonsNear = mongoTemplate.find(new Query(Criteria
                                  .where("loc")
                                  .near(point)
                                  .maxDistance(100)), Salon.class);
    

    在 2 公里范围内查找

    Double longitude = 4.368333;
    Double latitude = 51.1981366;
    Double distance  = 2.0;
    
    Circle myCircle = new Circle(new Point(longitude, latitude), new Distance(distance, Metrics.KILOMETERS));
    List<Salon> salonsWithinCircle = mongoTemplate.find(new Query(Criteria
                                       .where("loc")
                                       .withinSphere(myCircle)), Salon.class);
    

    在 2 公里范围内查找嵌套对象

    Circle myCircle = new Circle(new Point(longitude, latitude), new Distance(distance, Metrics.KILOMETERS));
    List<Salon> salonsWithinCircle = mongoTemplate.find(new Query(Criteria
                                       .where("address.loc")
                                       .withinSphere(myCircle)), Salon.class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      相关资源
      最近更新 更多