2013-10-18 47 views
3

我正在尋找一種方法將位置值插入到MongoDB中的集合。我正在使用MongoDB JAVA驅動程序。不幸的是,我無法這樣做。MongoDB - 如何將位置插入集合

集合已正確編入索引。這裏的問題是集合以包含double值的數組的形式接受位置。但我不確定是否有直接發送數組的方法,因爲只發送數組的引用而不是實際的內容。代碼 double latLong [] = {124.6682391,-17.8978304}; final BasicDBObject loc = new BasicDBObject(); loc.put(「type」,「Point」); loc.put(「coordinates」,latLong);

jsonObject.put("location", loc); 

添加時,當我嘗試打印它,我得到以下輸出。

"location" : { "type" : "Point" , "coordinates" : "[[email protected]"} 

這導致「無法從對象中提取地理鍵,格式錯誤?」錯誤。

我試着發送位置作爲一個數組列表。但是,這一次存儲的值作爲

"location" : { "type" : "Point" , "coordinates" : "[144.6682362, -37.8978302]"} 

但不能作爲

"location" : { "type" : "Point" , "coordinates" : [144.6682362, -37.8978302]} 

這又導致「無法提取對象地理按鍵,畸形幾何?:」錯誤。

還試圖Arrays.toString((經緯度))

這導致

" location" : { "type" : "Point" , "coordinates" : "[144.6682362, -37.8978302]"} 

因此相同的錯誤一次。

下面的URL表示這不能完成。 https://groups.google.com/forum/#!topic/mongodb-user/TUjAxag6yT4

但是我腦中還有一部分人說應該有辦法。

任何想法如何添加一個位置對象(這是一個數組持有雙值)到JSON對象,從而通過將JSON對象轉換爲DBObject的集合?

我不想找POJO庫,因爲我想堅持我的本地代碼。如果什麼都不能做,我可以跳到POJO圖書館。

回答

2

你必須創建jsonarray的座標,然後把它放在jsonObject中。嘗試是這樣的:

 double latLong[] = {124.6682391, -17.8978304}; 
     JSONArray jsonArray = new JSONArray(latLong); 
     JSONObject jobj = new JSONObject().put("type", "point"); 
     jobj.put("coordinates", jsonArray); 

     // below jsonObject_loc contains the jsonobject as you want.. 
     JSONObject jsonObject_loc = new JSONObject(); 
     jsonObject_loc.put("loc", jobj); 
     System.out.println(jsonObject_loc); 

     // but you have to store jobj in db as your query already has 'loc' object 
     BasicDBObject loc = new BasicDBObject(); 
     loc.put("loc", jobj.toString()); 

的JSON庫用於上述代碼是:java-json

+0

JSONArray jsonArray = new JSONArray(latLong);這會拋出一個錯誤「構造函數JSONArray(double [])未定義」 –

+0

你是否傳遞與上面定義的相同的latLong? – Jhanvi

+0

你能寫你在代碼中使用的latLong嗎? – Jhanvi

0

的問題是很老,但新我面臨着類似的問題,並發現使用蒙戈的Java做的簡單方法-driver-2.13.3。罐子從sonatype 下載的一種可能性是直接把座標在BasicDBObject喜歡這裏:

double latLong[]= {124.6682391, -17.8978304}; 
BasicDBObject loc1= new BasicDBObject("location", 
        new BasicDBObject("type", "Point") 
        .append("coordinates", latLong)); 

System.out.println("DEBUG: loc1 is: " + loc1.toString()); 

結果是:

DEBUG: loc1 is: { "location" : { "type" : "Point" , "coordinates" : [ 124.6682391 , -17.8978304]}} 

,我發現更好的另一種可能性是把BasicDBList像在這裏:

BasicDBList coords= new BasicDBList(); 
coords.add(Double.valueOf(124.6682391)); 
coords.add(Double.valueOf(-17.8978304)); 
BasicDBObject loc2= new BasicDBObject("location", 
    new BasicDBObject("type", "Point") 
    .append("coordinates", (latLong))); 

System.out.println("DEBUG: loc2 is: " + loc2.toString()); 

結果又是:

DEBUG: loc2 is: { "location" : { "type" : "Point" , "coordinates" : [ 124.6682391 , -17.8978304]}} 
相關問題