Java MongoDB 3.3.0 - List of mongoDB database collections

 Posted On  | Yashwant Chavan 

Like show collections shell command is used to display the list of collections, same way mongoDB Java driver provides method (database.listCollectionNames()) to display the list of collections from the selected database.

Maven Dependencies

Define mongo-java-driver maven dependencies in pom.xml

<dependencies>
 <dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongo-java-driver</artifactId>
        <version>3.3.0</version>
 </dependency>
</dependencies>

Connecting to database

A MongoDB client internally uses the connection pooling mechanism. It has one MongoClient instance for the entire JVM. To connect the local mongoDb database use host name "localhost" and default port number "27017".

 MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

Get the database instance

Once you are successfully connected, access the technicalkeeda database.

 MongoDatabase database = mongoClient.getDatabase("technicalkeeda");

List Of mongoDB Collections

You can get a list of the collections in a database using the database.listCollectionNames() method. It will return the MongoIterable object which is nothing but a results from an operation, such as a query, list of collections etc.

package com.technicalkeeda.app;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;

public class App {
    public static void main(String[] args) {
        new App().collectionNames();
    }

    public void collectionNames() {
        MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

        try {
            MongoDatabase database = mongoClient.getDatabase("technicalkeeda");

            MongoIterable <String> collections = database.listCollectionNames();
            for (String collectionName: collections) {
                System.out.println(collectionName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mongoClient.close();
        }
    }
}

Program Output

system.indexes //system collection
movies
animals
books
cars

Shell Output

show collections command is used to print a list of all collections for current database

> use technicalkeeda
switched to db technicalkeeda
> show collections
animals
books
cars
movies
system.indexes
>


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0425 seconds.