【问题标题】:cannot be cast to org.bson.BSONObject不能转换为 org.bson.BSONObject
【发布时间】:2015-12-18 09:55:47
【问题描述】:

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

不能转换为 org.bson.BSONObject

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

  • 鼠标移动
  • 鼠标移动
  • 鼠标移动
  • 点击
  • 滚动
  • 点击
  • pageLoad....//htttp://www......url(1)......e.x
  • 鼠标移动
  • 点击
  • pageLoad....//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);

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

【问题讨论】:

  • while((((BSONObject) db.getCollection("event")).get("type") != "pageLoad")) 看起来不对。您不能将 DBCollection 转换为 BSONObject。您确定应该查看实际的光标事件吗?

标签: java mongodb mongodb-java mongo-collection


【解决方案1】:

要使用光标循环查询结果,请使用以下代码:

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

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

if ("pageLoad".equals(documentInEventCollection.get("type")) {
    // do something
} else {
    // do something else
}

【讨论】:

    猜你喜欢
    • 2018-02-10
    • 2023-03-22
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多