0

I try to make this program but I get this error

cannot be cast to org.bson.BSONObject

I don't know if the structure of the program is fine. I want to do a program to search in the database (mongoDB) and print me all the events, but when I have a pageLoad event I want to check if it has a URL and to print it, else it should search again for the next event until again one event of pageLoad. So one loop like this. The result it have to be like this for example.

  • mouseMove
  • mouseMove
  • mouseMove
  • click
  • scroll
  • click
  • pageLoad....//htttp://www......url(1).....e.x
  • mouseMove
  • click
  • 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();
}
}
William
  • 33
  • 1
  • 10
  • `while((((BSONObject) db.getCollection("event")).get("type") != "pageLoad"))` looks wrong. You can't cast `DBCollection` to `BSONObject`. Surely you should be looking at the actual cursor event? – Ross Dec 18 '15 at 10:41

1 Answers1

2

To loop through the results of your query using the cursor, use the following code:

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

Further more, don't try to compare Strings with == or !=. That won't compare the actual string but the object reference. If you want to check if the type field of a document equals the string pageLoad, use the following code:

if ("pageLoad".equals(documentInEventCollection.get("type")) {
    // do something
} else {
    // do something else
}
hzpz
  • 7,536
  • 1
  • 38
  • 44