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

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: 2020-04-10T07:18:10+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements