2015-11-03 37 views
1

我正在開發一個Java驅動程序訪問一個MongoDB分片集羣。當我嘗試在數據庫"db"的集合"test"上執行find()方法時,它不返回任何內容。但是,我通過mongo客戶端檢查過該特定集合中有一些文檔。誰能幫忙?非常感謝。無法檢索MongoDB中的現有文檔

public class App { 
    public static void main(String[] args) { 
     /**** Connect to MongoDB ****/ 
     MongoClient mongo = new MongoClient(Arrays.asList(new ServerAddress(
      "10.110.198.147", 27017), new ServerAddress("10.110.198.160", 
      27017))); 
     /**** Get database ****/ 
     // if database doesn't exists, MongoDB will create it for you 
     DB db = mongo.getDB("db"); 

     /**** Get collection/table from 'testdb' ****/ 
     // if collection doesn't exists, MongoDB will create it for you 
     DBCollection coll = db.getCollection("test"); 

     BasicDBObject document = new BasicDBObject(); 
     document.put("count", "1000"); 
     coll.insert(document); 

     DBCursor cursor = coll.find(); 

     while (cursor.hasNext()) { 
     System.out.println(cursor.next()); 
     } 
    } 
} 
+0

等爲我理解你的代碼插入數據,但是沒有找到?或者也許它不會插入它?那麼也許你的IP地址或端口號有錯誤。 – wawek

回答

0

你能試試嗎?

FindIterable<Document> iterable = db.getCollection("restaurants").find(); 

iterable.forEach(new Block<Document>() { 
    @Override 
    public void apply(final Document document) { 
     System.out.println(document); 
    } 
}); 

發現它的文檔here

+0

謝謝你的回覆。我試過這個,但得到這個編譯錯誤:App.java:40:錯誤:不兼容的類型 FindIterable iterable = coll.find(); ^ 必需:FindIterable 找到:DBCursor – Jim