Reputation: 167
I want to run a $near
query on a collection through Java. I am not sure how to use QueryBuilder
or BasicDbObject
for this. What is the correct way to run $near
query through Java code?
Below is my code for document structure. "location" attribute stores type as point and coordinates stores the lat-long. I have created a 2dsphere index on this collection.
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])
Upvotes: 1
Views: 1221
Reputation: 2606
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/
Upvotes: 0