How to get the list of all the MongoDB databases using java?


In MongoDB, you can view the list of databases using the show dbs command

> show dbs
admin
config
local
myDatabase
sampleDatabase
students
test
testDB

In Java, you can get the list of all the databases in MongoDb using the getDatabaseNames() method.

Example

import com.mongodb.client.MongoIterable;
import com.mongodb.MongoClient;
public class ListOfDatabases {
   public static void main( String args[] ) {
      // Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Retrieving the list of collections
      MongoIterable<String> list = mongo.listDatabaseNames();
      for (String name : list) {
         System.out.println(name);
      }
   }
}

Output

admin
config
local
myDatabase
sampleDatabase
students
test
testDB

Updated on: 10-Apr-2020

846 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements