Search code examples
javamongodbmongo-java

MongoDB list available databases in java


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

On the windows shell I just do

show dbs

How can I do that in java and get back a list of all the available databases?


Solution

  • You would do this like so:

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

    That will simply give you a list of all of the database names available.

    You can see the documentation here.

    Update:

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

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