MongoDB - Java

MongoDB - PHP

MongoDB - Advanced

MongoDB - Useful Resources

MongoDB - Java - Listing All Collections



MongoDB provides MongoDatabase class to list all underlying collections.

Syntax

// connect to the database
MongoDatabase database = mongoClient.getDatabase("myDb");

// list all the collections
for (String name : database.listCollectionNames()) { 
   System.out.println(name); 
}

Listing all Collections

To list all collections, we first need to connect to a database and then list all the collections as shown below −

package com.tutorialspoint.mongodb;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;

public class MongoDBTester {

   public static void main(String args[]) {

      String uri = "mongodb://localhost:27017/";

      try (MongoClient mongoClient = MongoClients.create(uri)) {
         MongoDatabase database = mongoClient.getDatabase("myDb");

         // Creating a collection 
         database.createCollection("sampleCollection"); 

         // List all collections
         for (String name : database.listCollectionNames()) { 
            System.out.println(name); 
         } 
      }
   }
}

Output

Now, let's compile and run the above program to list collections of our database myDb.

On executing, the above program gives you the following output.

sampleCollection
Advertisements