MongoDB - Java | $near 的使用

MongoDB - Java | Use of $near

我正在 MongoDB Collection 中保存一些帖子,如下所示:

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

我想获取特定比例的帖子,比方说 2km。

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

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

的 collection
        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();
        }

但仍然没有得到任何结果..游标没有文件。 我也收到这个错误

03-17 01:34:05.489 1786-1805/? W/System.err: com.mongodb.MongoQueryException: Query failed with error code 17007 and error message 'Unable to execute query: error processing query: ns=posts2.texts2 limit=0 skip=0 03-17 01:34:05.489 1786-1805/? W/System.err: Tree: GEONEAR field=loc maxdist=100 isNearSphere=0 03-17 01:34:05.489 1786-1805/? W/System.err: Sort: {} 03-17 01:34:05.489 1786-1805/? W/System.err: Proj: {} 03-17 01:34:05.489 1786-1805/? W/System.err: planner returned error: unable to find index for $geoNear query' on server ds011439.mlab.com:11439

我向您发送 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 米(2 公里)以内的所有位置

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

在您的 json 格式中,您的 "loc" 字段类型为:点。 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 是文档。

试一试。

首先打开与数据库的 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);

半径2km内查找

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);