Code Bug Fix: How to retrieve collections name using mongodb api Java?

Original Source Link

I’m trying to retrieve the collections name in my program
i created this method for this

        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 ----
    } catch (MongoException | ClassCastException e) {
        System.err.println("Exception occurred while insert Value using getListOfCollections  ");
    return list;

but for a reason it keep crashing
its also crashed when I used:

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

the uri is working and i’m capable of inserting Documents

apparently my IP has changed and I couldn’t access the database hence I couldn’t retrieve the collections (and insert data).

lesson – make sure your IP is correct in the MongoDB -Network access.
BTW, this method works!

Tagged : / / /

Leave a Reply

Your email address will not be published. Required fields are marked *