Java Mongodb 简明教程

Java & MongoDB - Show Databases

要显示数据库,可以使用 MongoClient.listDatabaseNames() 方法获取所有数据库的名字。

To show databases, you can use MongoClient.listDatabaseNames() method to get the name of all the databases.

MongoIterable<String> list = mongoClient.listDatabaseNames();
for (String name : list) {
   System.out.println(name);
}

由于我们在 Connect Database 章节中创建了一个空数据库,我们需要插入一个文档,以便在 MongoDB 数据库列表中显示它。

As we have created an empty database in Connect Database chapter, we need to insert a document to make it visible in mongodb database list.

Example

以下是列出数据库的代码片段 −

Following is the code snippet to list down database −

import org.bson.Document;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");
      database.createCollection("sampleCollection");

      // Retrieving a collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      Document document = new Document("title", "MongoDB")
         .append("description", "database")
         .append("likes", 100)
         .append("url", "http://www.tutorialspoint.com/mongodb/")
         .append("by", "tutorials point");

      //Inserting document into the collection
      collection.insertOne(document);

      MongoIterable<String> list = mongoClient.listDatabaseNames();
      for (String name : list) {
         System.out.println(name);
      }
   }
}

现在,我们按照以下步骤编译并运行上述程序。

Now, let’s compile and run the above program as shown below.

$javac Tester.java
$java Tester

Output

在执行上述程序时,您将得到以下输出。

On executing, the above program gives you the following output.

admin
config
local
myDb