I try to read out all fields of an array of a document in MongoDB. I tried to adapt a posted solution from Stackoverflow to my use case, but I get the error message:
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.mongodb.BasicDBList
at Connector.getTopics(Connector.java:249)
Basically I want to read out the array in "Topics" of the first document in the collection "Topics" and save the values to an arrayList and return it.
public ArrayList<String> getTopics() throws RemoteException {
// TODO Auto-generated method stub
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongoClient.getDatabase("JMS");
MongoCollection<Document> collection = database.getCollection("Topics");
ArrayList<String> list = new ArrayList<String>();
Document document = collection.find(eq("_id", 1.0)).first();
ListIterator<Object> topics = ((BasicDBList) document.get("Topics")).listIterator();
while(trustedList.hasNext()){
Object nextItem = topics.next();
list.add((String) nextItem);
}
return list;
}
I do not completely understand the posted solution to get all values of the array, so I am a bid confused how to correct the cast error.
document.get("Topics")).listIterator()returns anArrayListwhy don't you just use it as such, instead of casting it toBasicDBList(which might be deprecated API, just a guess)