0

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.

1
  • I'm not sure about MongoDB, but if the method document.get("Topics")).listIterator() returns an ArrayList why don't you just use it as such, instead of casting it to BasicDBList (which might be deprecated API, just a guess) Commented Aug 1, 2017 at 13:02

1 Answer 1

0

I think that you need to store topics in a BasicDBList object:

 BasicDBList topics = (BasicDBList) document.get("Topics");

Then you can iterate it and store into your array:

List<String> result = new ArrayList<String>();
for(Object element: topics) {
     result.add((String) element);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Im a bid confused, where is topicsMongo actually used?
I mean that BasicDBList is like a Java List so you don't need get the iterator, you can iterate on it in a "foreach", like an Array: I wrote 'list' when I should wrote 'topicsMongo'. Now the answer is edited, thanks to @the4kman
mhh it says: "java.util.ArrayList cannot be cast to com.mongodb.BasicDBList"

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.