mongodbjakarta-eemongo-collection

Java Application not recognizing my collections in my MongoDB databases.


I am creating a simple web application and I am attempting to connect the application to MongoDB. Here is the class where I am establishing the connection.

public class JavaMongoDBConnection {

public static void main(String[] args) {
    try {
    MongoClient mongoClient = null;

        mongoClient = new MongoClient();

    List<String> databases = mongoClient.getDatabaseNames();

    for(String dbName: databases) {
        System.out.println("Databases: " + dbName);

        DB db  = mongoClient.getDB(dbName);

        Set<String> collections = db.getCollectionNames();

        for(String colName : collections) {
            System.out.println("\t + Collection: "+colName);

        }

    }
    mongoClient.close();


    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

} }

When I run this class as a Java application, this is my result

Databases: admin Databases: budget Databases: config Databases: db Databases: local Databases: myTestDB

However, when I go to terminal and I run the following commands, here are my results.

  1. show dbs

Response: admin 0.000GB budget 0.000GB config 0.000GB db 0.000GB local 0.000GB myTestDB 0.000GB

  1. use myTestDB

  2. show collections

Response: Budget budget myCollection

So, why are Budget, budget, and myCollection not showing up when I run this java application??


Solution

  • If you're using the current version of the MongoDB Java Driver (currently 3.7), use MongoDatabase instead of DB:

    MongoClient mongoClient = new MongoClient();
    
    for(String databaseName : mongoClient.listDatabaseNames()) {
        System.out.println("Database: " + databaseName);
    
        MongoDatabase db = mongoClient.getDatabase(databaseName);
    
        for(String colName : db.listCollectionNames()) {
            System.out.println("\t + Collection: " + colName);
        }
    }
    
    mongoClient.close();
    

    The above code should have an output similar to the following:

    Database: admin
             + Collection: system.version
    Database: config
             + Collection: system.sessions
    Database: local
             + Collection: startup_log
    Database: test
             + Collection: testcoll1
             + Collection: testcoll2