10

i have the following code :

DBCollection collsc = db.getCollection("StudentCourses") ;
BasicDBObject querysc = new BasicDBObject("StudentID",id ); 
DBCursor curssc = collsc.find(querysc);

while(curssc.hasNext()) {

    DBObject e = curssc.next();
    System.out.println("You are currently registered for the following modules: ") ; 
    System.out.println(e.get("CoursesRegistered")) ; 

}

This outputs:

You are currently registered for the following modules: 
[ "DigitalLogic" "OperatingSystems" , "FundamentalsCSE"]

However i want only the values to be returned from the array, i.e, DigitalLogic, OperatingSystems and FundamentalsCSE. I will use these values to populate a JList. Help please?

1 Answer 1

17

Try to use

BasicDBList e = (BasicDBList) curssc.next().get("CoursesRegistered");

instead of

DBObject e = curssc.next();

and then get value from e.getIndex(index);

Sign up to request clarification or add additional context in comments.

4 Comments

It doesn't work. I get exception as follows : Exception in thread "main" java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to com.mongodb.BasicDBList at modules.RegistrationSystem.main(RegistrationSystem.java:80)
Still exceptions. Exception in thread "main" java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [CoursesRegistered] at org.bson.types.BasicBSONList._getInt(BasicBSONList.java:161) at org.bson.types.BasicBSONList._getInt(BasicBSONList.java:152) at org.bson.types.BasicBSONList.get(BasicBSONList.java:104) at modules.RegistrationSystem.main(RegistrationSystem.java:82)
This did it. DBCollection collsc = db.getCollection("StudentCourses") ; BasicDBObject querysc = new BasicDBObject("StudentID",id ); DBCursor curssc = collsc.find(querysc); while(curssc.hasNext()) { //DBObject e = curssc.next(); BasicDBList e = (BasicDBList) curssc.next().get("CoursesRegistered"); System.out.println("You are currently registered for the following modules: ") ; for (int i=0;i<e.size();i++) { System.out.println(e.get(i)) ; } }
How do i do this this with mongo-java 3.0 driver ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.