MongoDB列出Java中可用的数据库 [英] MongoDB list available databases in java

查看:308
本文介绍了MongoDB列出Java中可用的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一种算法,该算法将遍历Java中所有可用的Mongo数据库.

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

在Windows shell上,我只是做

On the windows shell I just do

show dbs

我该如何在Java中执行此操作并获取所有可用数据库的列表?

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

推荐答案

您将这样做:

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

这只会为您提供所有可用数据库名称的列表.

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

您可以在此处查看文档

更新:

正如下面的@CydrickT所述,getDatabaseNames已被弃用,因此我们需要切换到:

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

这篇关于MongoDB列出Java中可用的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆