首页 > 解决方案 > 如何使用 mongodb api Java 检索集合名称?

问题描述

我正在尝试在我的程序中检索集合名称我为此创建了此方法

        public static LinkedList<String> getListOfCollections() {
    LinkedList<String> list = new LinkedList<>();
    try (MongoClient mongoClient = new MongoClient(uri)) {
        MongoDatabase db = mongoClient.getDatabase("db name");
            MongoIterable<String> mList = db.listCollectionNames();
               for (String string : mList) { // ---- crash here ----
            list.add(string);
        }
    } catch (MongoException | ClassCastException e) {
        System.err.println("Exception occurred while insert Value using getListOfCollections  ");
    }
    return list;
}

但由于某种原因,它不断崩溃,当我使用时它也崩溃了:

 MongoCursor<String> tmp = mList.iterator();

ps-uri 正在工作,我可以插入文档

标签: javamongodbiteratorcursor

解决方案


显然我的 IP 已更改,我无法访问数据库,因此我无法检索集合(并插入数据)。

课程 - 确保您的 IP 在 MongoDB 网络访问中是正确的。顺便说一句,这种方法有效!


推荐阅读