MongoDB list of available databases in java

I am writing an algorithm that will go through all available Mongo databases in java.

In windows shell i just do

show dbs

How can I do this in java and return a list of all available databases?

+5
source share
2 answers

You would do it like this:

MongoClient mongoClient = new MongoClient();
List<String> dbs = mongoClient.getDatabaseNames();

This will just give you a list of all available database names.

You can see the documentation here .

Update:

As @CydrickT mentioned below, is getDatabaseNamesalready deprecated, so we need to switch to:

MongoClient mongoClient = new MongoClient();
MongoCursor<String> dbsCursor = mongoClient.listDatabaseNames().iterator();
while(dbsCursor.hasNext()) {
    System.out.println(dbsCursor.next());
}
+14
source

For everyone who comes here because the method is getDatabaseNames();outdated / inaccessible, here is a new way to get this information:

MongoClient mongoClient = new MongoClient();
MongoCursor<String> dbsCursor = mongoClient.listDatabaseNames().iterator();
while(dbsCursor.hasNext()) {
    System.out.println(dbsCursor.next());
}

, , getDatabaseNames():

public List<String> getDatabaseNames(){
    MongoClient mongoClient = new MongoClient(); //Maybe replace it with an already existing client
    List<String> dbs = new ArrayList<String>();
    MongoCursor<String> dbsCursor = mongoClient.listDatabaseNames().iterator();
    while(dbsCursor.hasNext()) {
        dbs.add(dbsCursor.next());
    }
    return dbs;
}
+7