English 中文(简体)
Java & MongoDB - Show Databases
  • 时间:2024-12-22

Java & MongoDB - Show Databases


Previous Page Next Page  

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


MongoIterable<String> pst = mongoCpent.pstDatabaseNames();
for (String name : pst) {
   System.out.println(name);
}

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

Example

Following is the code snippet to pst down database −


import org.bson.Document;

import com.mongodb.cpent.MongoCpent;
import com.mongodb.cpent.MongoCpents;
import com.mongodb.cpent.MongoCollection;
import com.mongodb.cpent.MongoDatabase;
import com.mongodb.cpent.MongoIterable;

pubpc class Tester {
   pubpc static void main(String[] args) {
      // Creating a Mongo cpent 
      MongoCpent mongoCpent = MongoCpents.create("mongodb://localhost:27017");
      MongoDatabase database = mongoCpent.getDatabase("myDb");
      database.createCollection("sampleCollection");

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

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

      MongoIterable<String> pst = mongoCpent.pstDatabaseNames();
      for (String name : pst) {
         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
Advertisements