MongoDB list available databases in java

久未见 提交于 2019-12-12 10:43:16

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/15416559/mongodb-list-available-databases-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!