0

我尝试制作这个程序,但我收到了这个错误

不能转换为 org.bson.BSONObject

我不知道程序的结构是否良好。我想做一个程序来搜索数据库(mongoDB)并打印我所有的事件,但是当我有一个pageLoad事件时我想检查它是否有一个 URL 并打印它,否则它应该再次搜索下一个事件直到再次发生的一个事件pageLoad。所以像这样一个循环。例如,结果必须是这样的。

  • 鼠标移动
  • 鼠标移动
  • 鼠标移动
  • 点击
  • 滚动
  • 点击
  • pageLoad....//htttp://www......url(1)......ex
  • 鼠标移动
  • 点击
  • pageLoad....//htttp://www......url(2)......ex

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

if (cursorEvents.hasNext()) {

  while ((((BSONObject) db.getCollection("event")).get("type") != "pageLoad")) {

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


    if (((BSONObject) db.getCollection("event")).get("type") == "pageLoad") {

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

    }
  }
}
mongoClient.close();
}
}
4

1 回答 1

2

要使用游标遍历查询结果,请使用以下代码:

while (cursorEvents.hasNext()) {
    DBObject documentInEventCollection = cursorEvents.next();
    // do stuff with documentInEventCollection
}

此外,不要试图将Strings 与==or进行比较!=。那不会比较实际的字符串而是对象引用。如果要检查type文档的字段是否等于字符串pageLoad,请使用以下代码:

if ("pageLoad".equals(documentInEventCollection.get("type")) {
    // do something
} else {
    // do something else
}
于 2015-12-18T12:10:09.077 回答