How to list all the Collections in a MongoDB database using Java?

JavaObject Oriented ProgrammingProgramming

You can print a list of all the existing collections in a database using show collections.

Example

Assume we have created 3 collections in a MongoDB database as shown below −

> use sampleDatabase
switched to db sampleDatabase
> db.createCollection("students")
{ "ok" : 1 }
> db.createCollection("teachers")
{ "ok" : 1 }
> db.createCollection("sample")
{ "ok" : 1 }

Following query lists all the collections in the database −

> use sampleDatabase
switched to db sampleDatabase
> show collections
sample
students
teachers

Using Java program

In Java, you can get the names of all collections in the current database using the listCollectionNames() method of the com.mongodb.client.MongoCollection interface.

Therefore to list all the collections in a database in MongoDB using Java program −

  • Make sure you have installed MongoDB in your system

  • Add the following dependency to its pom.xml file of your Java project.

<dependency>
   <groupId>org.mongodb</groupId>
   <artifactId>mongo-java-driver</artifactId>
   <version>3.12.2</version>
</dependency>
  • Create a MongoDB client by instantiating the MongoClient class.

  • Connect to a database using the getDatabase() method.

  • Get the list of the collections using the listCollectionNames() method.

Example

import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.MongoClient;
public class ListOfCollection {
   public static void main( String args[] ) {
      // Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Connecting to the database
      MongoDatabase database = mongo.getDatabase("mydatabase");
      //Creating multiple collections
      database.createCollection("sampleCollection1");
      database.createCollection("sampleCollection2");
      database.createCollection("sampleCollection3");
      database.createCollection("sampleCollection4");
      //Retrieving the list of collections
      MongoIterable<String> list = database.listCollectionNames();
      for (String name : list) {
         System.out.println(name);
      }
   }
}

Output

sampleCollection3
sampleCollection2
sampleCollection4
sampleCollection1
raja
Published on 08-Apr-2020 16:58:26
Advertisements