在Java中从MongoDB检索数组
我尝试读取MongoDB中文档数组的所有字段。 我试图将发布的解决方案从Stackoverflow改编为我的用例,但我收到了错误消息:
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.mongodb.BasicDBList
at Connector.getTopics(Connector.java:249)
基本上,我想读取集合“Topics”中第一个文档的“Topics”中的数组,并将值保存到arrayList中并返回它
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;
}
我不完全理解发布的解决方案来获取数组的所有值,因此我对如何纠正强制转换错误感到困惑
# 1 楼答案
我认为您需要将主题存储在BasicDBList对象中:
然后您可以迭代它并将其存储到数组中: