MongoDB list available databases in java

后端 未结 2 1594
孤城傲影
孤城傲影 2021-01-17 22:40

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

2条回答
  •  感情败类
    2021-01-17 23:06

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

提交回复
热议问题