- Java & MongoDB - Home
- Java & MongoDB - Overview
- Java & MongoDB - Environment Setup
- Java & MongoDB Examples
- Java & MongoDB - Connect Database
- Java & MongoDB - Show Databases
- Java & MongoDB - Drop Database
- Java & MongoDB - Create Collection
- Java & MongoDB - Drop Collection
- Java & MongoDB - Display Collections
- Java & MongoDB - Insert Document
- Java & MongoDB - Select Document
- Java & MongoDB - Update Document
- Java & MongoDB - Delete Document
- Java & MongoDB - Embedded Documents
- Java & MongoDB - Referenced Documents
- Java & MongoDB - Limiting Records
- Java & MongoDB - Sorting Records
Java & MongoDB - Display Collections
To display list of collections, you can use database.listCollectionNames() method to get the list of collection names in the databases.
MongoIterable<String> collections = database.listCollectionNames();
Example
Following is the code snippet to display list of collections −
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// Get the database
MongoDatabase database = mongoClient.getDatabase("myDb");
// Create the collection
database.createCollection("sampleCollection");
// Get the list of collection names
MongoIterable<String> collections = database.listCollectionNames();
for (String name : collections) {
System.out.println(name);
}
}
}
Now, let's compile and run the above program as shown below.
$javac Tester.java $java Tester
Output
On executing, the above program gives you the following output.
sampleCollection
Advertisements