我想通过Java对集合运行$ near查询。我不知道如何使用QeuryBuilder或BasicDbObject。通过Java代码运行$ near查询的正确方法是什么。下面是我的文档结构代码。 “location”属性将类型存储为点,坐标存储lat-long。我在这个集合上创建了一个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])
答案 0 :(得分:0)
首先,您需要一个maxDistance和一个参考点来计算附近的文档。下面的代码显示了如何构建一个DBObject来查询文档附近。
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();
这将导致json:
{
"location": {
"$maxDistance": 100,
"$near": {
"$geometry": {
"type": "Point",
"coordinates": [
0,
0
]
}
}
}
}
如果您使用的是mongodb 2.2,则上述代码无效。我必须使用以下内容:
double[] coords = new double[2];
long distance = 100;
DBObject query = BasicDBObjectBuilder.start()
.push("location")
.add("$maxDistance", distance)
.add("$near", coords)
.get();
json将是:
{
"location" : {
"$maxDistance" : 100,
"$near" : [
0,
0
]
}
}
您可以在此处找到有关近端查询的更多信息: