William
William

Reputation: 33

cannot be cast to org.bson.BSONObject

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.


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

Upvotes: 0

Views: 7049

Answers (1)

hzpz
hzpz

Reputation: 7911

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
}

Upvotes: 2

Related Questions