2013-07-03 140 views
0

我想通過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

首先,您需要一個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 
     ] 
    } 
} 

您可以找到附近的查詢,這裏更多的信息:

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

+0

值得指出的是,這代碼將在MongoDB版本2.4上工作,但不是2.2。 – Trisha

+0

答案已更新。謝謝Trisha。 –