有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java My MongoDB日志记录系统的行为与预期不同。为什么?

我正在开发一个MongoDB日志系统,但它的行为并不像我预期的那样。我不知道程序的结构是否良好
我想在数据库(MongoDB)中搜索并打印所有事件,但是当我有pageLoad事件时,我想检查它是否有URL并打印它,否则它应该再次搜索下一个事件并尝试相同的行为,作为循环

我预期的结果是这样的,例如:

  • 鼠标移动
  • 鼠标移动
  • 鼠标移动
  • 点击
  • 卷轴
  • 点击
  • 页面加载//htttp://www......url(1).....e、 x
  • 鼠标移动
  • 点击
  • 页面加载//htttp://www......url(2).....e、 x

代码如下:

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

但是当我运行程序时,我得到的结果是这样的,例如:

  • 窗口大小
  • 鼠标移动
  • 点击
  • 点击

。。。它就停在那里


怎么了


共 (1) 个答案

  1. # 1 楼答案

    您在循环中调用了cursorEvents.next()三次,而不是一次。每次调用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());             
       }                
    

    }