2015-12-21 54 views
0

我正在使用MongoDB日誌記錄系統,但它並沒有按照我的預期行事。我不知道程序的結構是否正常。
我想在數據庫(MongoDB)中搜索並打印所有事件,但是當我有一個pageLoad事件時,我想檢查它是否有URL並打印它,否則它應該再次搜索下一個事件並嘗試相同的行爲,作爲一個循環。我的MongoDB日誌記錄系統的行爲與預期不同。爲什麼?

結果我的預期就必須是這樣的,例如:

  • 的mouseMove
  • 的mouseMove
  • 的mouseMove
  • 點擊
  • 滾動
  • 點擊
  • 頁面加載。 ... // htttp://www......url(1)..... ex
  • 的mouseMove
  • 點擊
  • 頁面加載.... // HTTTP://www......url(2).....前

這是代碼:

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); 

    while (cursorEvents.hasNext()) { 
     DBObject documentInEventCollection = cursorEvents.next(); 

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

     if ("pageLoad".equals(documentInEventCollection.get("type"))) { 

      System.out.println(cursorEvents.next().get("url").toString()); 
     } else { 

      System.out.println(cursorEvents.next().get("type").toString());    
     }     
    } 
    mongoClient.close(); 

但是當我運行程序,結果我得到的是這樣的,例如:

  • windowSize
  • 的mouseMove
  • clickUp
  • 點擊

...它停在那裏。


什麼是錯?

+0

添加一個try-catch在你的while()循環,並打印出你可能會得到任何異常。 – Jan

+1

請閱讀 - http://stackoverflow.com/help/how-to-ask –

回答

1

你在循環中三次呼叫cursorEvents.next(),而不是一次。每次你打電話到下一個()時,你會......去下一個元素。

使用您documentInEventCollection變量,而不是:

while (cursorEvents.hasNext()) { 
    DBObject documentInEventCollection = cursorEvents.next(); 

    System.out.println(documentInEventCollection.get("type").toString()); 

    if ("pageLoad".equals(documentInEventCollection.get("type"))) { 

     System.out.println(documentInEventCollection.get("url").toString()); 
    } else { 

     System.out.println(documentInEventCollection.get("type").toString());    
    }     

}

+0

非常感謝!用這種方法我得到了正確的結果! – William

相關問題