1

我想通过 Java 对集合运行 $near 查询。我不确定如何为此使用 QeuryBuilder 或 BasicDbObject。通过 Java 代码运行 $near 查询的正确方法是什么。下面是我的文档结构代码。“位置”属性将类型存储为点,坐标存储经纬度。我在这个集合上创建了一个 2dsphere 索引。

BasicDBObject doc = new BasicDBObject("attr1", nextLine[0])
                          .append("attr2", nextLine[1])
                          .append("edge-metro-code", nextLine[6])
                          .append("location", new BasicDBObject("type", "Point")
                                                        .append("coordinates",latLong)) 
                          .append("attr3", nextLine[9])
                          .append("attr4", nextLine[10])
4

1 回答 1

0

First you'll need a maxDistance and a referential point to calculate near documents. The code bellow shows how to build a DBObject to query near documents.

double[] coords = new double[2];
long distance = 100;

DBObject query = BasicDBObjectBuilder.start()
    .push("location")
        .add("$maxDistance", distance)
        .push("$near")
            .push("$geometry")
                .add("type", "Point")
                .add("coordinates", coords)
    .get();

This will result in that json:

{
    "location": {
        "$maxDistance": 100,
        "$near": {
            "$geometry": {
                "type": "Point",
                "coordinates": [
                    0,
                    0
                ]
            }
        }
    }
}

If you're using mongodb 2.2, the code above will not work. I have to use the following:

double[] coords = new double[2];
long distance = 100;

DBObject query = BasicDBObjectBuilder.start()
    .push("location")
        .add("$maxDistance", distance)
        .add("$near", coords)
    .get();

The json will be:

{
    "location" : {
        "$maxDistance" : 100,
        "$near" : [
            0,
            0
        ]
    }
}

You can find more informations about near queries here:

http://docs.mongodb.org/manual/reference/operator/near/

于 2013-07-04T11:10:15.453 回答