10

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?

2
  • Are you using the standard driver ? Commented Mar 14, 2013 at 17:49
  • Yes i am using the standard one. Commented Mar 14, 2013 at 17:50

2 Answers 2

20

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());
}
Sign up to request clarification or add additional context in comments.

1 Comment

How did i miss that ! Yea that did the trick ! thank you loads !
10

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;
}

1 Comment

This is true,thanks so much for the answer ,this should be the correct answer so there will be no confusion.Cheers,best of luck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.