2015-12-17 126 views
0

我正在數據庫中搜索URL,但使用此代碼搜索我不能。爲什麼?通常情況下,我想打印所有類型和該數據庫中存在的URL。當我只有打印類型正在工作,但打印URL沒有任何打印。與java一起使用mongodb

MongoClient mongoClient; 
DB db; 

mongoClient = new MongoClient("localhost", 27017); 
db = mongoClient.getDB("behaviourDB_areas");  


DBCollection cEvent = db.getCollection("event"); 

    BasicDBObject orderBy = new BasicDBObject(); 
    orderBy.put("timeStamp",1); 


    DBCursor cursorEvents = null; 

    BasicDBObject searchQuery = new BasicDBObject(); 
    searchQuery.put("user_id", "55b20db905f333defea9827f"); 

    cursorEvents = cEvent.find(searchQuery).sort(orderBy); 

     int count=0; 

     if(cursorEvents.hasNext()){ 

      while(cursorEvents.hasNext()){ 

       count++;   

       System.out.println(cursorEvents.next().get("type").toString()); 
       System.out.println(cursorEvents.next().get("url").toString()); 
       System.out.println(count); 
      } 
     } 

     mongoClient.close(); 
    } 
} 
+2

什麼是不工作?有沒有錯誤信息?你期望發生什麼?你使用什麼類型的收藏?數據如何看起來像完全一樣? –

+0

非常感謝您的答覆.....我是新的這一切...與MongoDB ...與Java ....我試圖! – William

+0

只是基本的計算器指南;) –

回答

0

cursor.next()只能調用一次,稱這是第二次將返回下一個文檔。 documentation

NullPointerException可能被拋出,因爲下一個文件不存在或get("url")返回null

以下代碼段應解決這兩個問題。

MongoClient mongoClient = new MongoClient("localhost", 27017); 
    MongoDatabase db = mongoClient.getDatabase("behaviourDB_areas"); 
    MongoCollection cEvent = db.getCollection("event", Document.class); 

    MongoCursor<Document> cursorEvents = cEvent 
      .find(new BasicDBObject("user_id", "55b20db905f333defea9827f")) 
      .sort(new BasicDBObject("timeStamp",1)) 
      .iterator(); 

    int count = 0; 

    if(cursorEvents.hasNext()) { 
     Document doc = cursorEvents.next(); 
     System.out.println(doc.getString("type")); 
     if (doc.containsKey("url")) { 
      System.out.println(doc.getString("url")); 
     } 
     System.out.println(++count); 
    } 

    cursorEvents.close(); 
    mongoClient.close();