How to List Database in MongoDB using Java

List Database in MongoDB using Java

In this example, We will show you simple program about, How to List Database in MongoDB using Java. The output were shared in the same post.

Example Program

package com.dineshkrish.mongo;

import java.util.List;

import com.mongodb.MongoClient;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class GetDBList {

	public static void main(String[] args) {
		
		
		final String HOST_NAME = "localhost";
		final int PORT = 27017;
		
		// getting the connection
		MongoClient client = new MongoClient(HOST_NAME, PORT);
		
		// get the list of database
		List<String> dbList = client.getDatabaseNames();
		
		// iterating using for each 
		for(String db : dbList) {
			
			// printing the db name
			System.out.println(db);
		}
		
		// closing the connection
		client.close();
		
	}
}

Output

demo1
demo2
demo3
dineshkrish
local

References

1. MongoDB Java API Documentation
2. JavaDoc – MongoClient Class
3. JavaDoc – List Interface