2015-12-18 68 views
0

我尽量让这个计划,但我得到这个错误不能转换为org.bson.BSONObject

不能转换到org.bson.BSONObject

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

  • 的mouseMove
  • 的mouseMove
  • 的mouseMove
  • 点击
  • 滚动
  • 点击
  • 页面加载.... // HTTTP://www......url( 1)..... ex
  • mouseMove
  • click
  • 页面加载.... // 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); 

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

'而((((BSONObject)db.getCollection(“事件”))获得(“型“)!=”pageLoad“))'看起来不对。您不能将'DBCollection'强制转换为'BSONObject'。当然,你应该看看实际的光标事件? – Ross

回答

2

要遍历您的查询结果使用光标,使用下面的代码:

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

更进一步,不要试图用==!=比较String秒。这不会比较实际的字符串和对象引用。如果您想检查文档的type场等于字符串pageLoad,使用下面的代码:

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

非常感谢您的支持......我会尽力...谢谢!!!! – William

相关问题