Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 536
Max Doumit Avatar asked Mar 14 '13 17:03

Max Doumit


People also ask

How do I get a list of databases in MongoDB?

If you want to check your databases list, use the command show dbs. Your created database (mydb) is not present in list. To display database, you need to insert at least one document into it. In MongoDB default database is test.

Is used to list all the databases in MongoDB?

Listing all the databases in mongoDB console is using the command show dbs .

What are the default databases in MongoDB?

Default database of MongoDB is 'db', which is stored within data folder.


2 Answers

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());
}
like image 117
jjnguy Avatar answered Oct 16 '22 05:10

jjnguy


For anyone who comes here because the method getDatabaseNames(); is deprecated / not available, here is the new way to get this information:

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

Here is a method that returns the list of database names like the previous getDatabaseNames() method:

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;
}
like image 41
GammaOmega Avatar answered Oct 16 '22 04:10

GammaOmega