2013-06-20 16 views
0

我試圖創建一個樹來存儲路徑有序信息,例如: ... /數據/汽車/豐田 ... /數據/汽車/菲亞特MongoDB的樹父引用

我發現的問題是Java語法本身,我如何創建父母和孩子? 我已經仔細閱讀下面的鏈接,但我仍然無法發展什麼,我需要在Java: http://docs.mongodb.org/manual/tutorial/model-tree-structures/ http://www.codeproject.com/Articles/521713/Storing-Tree-like-Hierarchy-Structures-With-MongoD

能否請您爲我提供了一個簡單的Java代碼片斷,允許創建樹+創建父併爲該父母創建一個孩子?

非常感謝您提前。

我現在想這個創建根:

DBCollection coll = db.getCollection(DataColl); 
BasicDBObject data = new BasicDBObject("_id", appId); 
data.put("path", null); 
coll.insert(data); 

,這創造了孩子的:

public boolean insertIntoDocument(String appId, String url, String data) { 
    DBCollection coll = db.getCollection(DataColl); 
    String[] array = url.split("/"); 
    BasicDBObject obj = new BasicDBObject("_id", array[array.length-1]); 
    for(int i = 0; i < array.length; i++){ 
     if(i == array.length-1) 
      obj.put("path", array[i]); 
     else 
      obj.put("path", array[i]+","); 
    } 
    coll.insert(obj); 
    return true; 

回答

0

我最終找到我自己的答案,希望這將幫助一些未來的新手。這段代碼收到一個url,比如a/b/c並創建一棵樹。我使用appId作爲root用戶,你可以使用像用戶標識符(每個用戶獲得它的url)等等。

public boolean insertIntoDocument(String appId, String url, String data) { 
    DBCollection coll = db.getCollection(DataColl); 
    String[] array = url.split("/"); 
    String tempURL = appId; 
    for (int i = 0; i < array.length; i++) { 
     BasicDBObject obj = new BasicDBObject("_id", array[i]); 
     if (i == array.length - 1) { 
      tempURL += ","+array[i]; 
      obj.put("path", tempURL); 
      obj.append("data", data); 
     } else { 
      tempURL += ","+array[i]; 
      obj.put("path", tempURL); 
     } 
     if(!elementExistsInDocument(appId, tempURL)) 
      coll.insert(obj); 
    } 
    return true;