Java应用无法识别MongoDB数据库中的集合问题排查
myTestDB 我正在创建一个简单的Web应用,尝试将其连接到MongoDB。以下是建立连接的JavaMongoDBConnection类代码:
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(" + Collection: "+colName); } } mongoClient.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
运行该Java应用后,能列出admin、budget、config、db、local、myTestDB数据库,但看不到myTestDB中的Budget、budget、myCollection集合。而在终端执行show dbs、use myTestDB、show collections命令时,能正常看到这些集合。请问为何Java应用中无法显示这些集合?
Hey there, I’ve run into this exact issue before—let’s break down the likely causes and fixes:
1. Missing Authentication for myTestDB
Chances are, your terminal session is already authenticated to access myTestDB, but your Java code is connecting anonymously. MongoDB restricts access to non-system databases by default in many setups, so an unauthenticated connection might not have permission to list collections in myTestDB.
Fix this by adding credentials to your MongoClient setup:
import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import java.util.Arrays; // ... inside your try block MongoCredential credential = MongoCredential.createCredential( "your-username", "myTestDB", "your-password".toCharArray() ); MongoClient mongoClient = new MongoClient( new ServerAddress(), Arrays.asList(credential) );
2. Old Driver API Behavior Limitations
You’re using the legacy MongoDB Java driver API (the DB class and getCollectionNames() method), which has a quirk: in some versions, it only returns collections that contain at least one document. The terminal’s show collections command shows empty collections, but the old API might skip them.
Quick test: Insert a dummy document into one of the missing collections, then re-run your Java code. If the collection shows up, this was the issue.
3. Driver-Server Version Incompatibility
If your MongoDB server is on a newer version (like 4.x+) but you’re using an outdated 2.x Java driver, there can be compatibility gaps that prevent proper collection listing.
The fix here is to upgrade to the latest compatible driver and switch to the modern API:
import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoIterable; public class JavaMongoDBConnection { public static void main(String[] args) { try (var mongoClient = MongoClients.create()) { // Iterate databases or target myTestDB directly MongoDatabase db = mongoClient.getDatabase("myTestDB"); MongoIterable<String> collectionNames = db.listCollectionNames(); System.out.println("Collections in myTestDB:"); for (String colName : collectionNames) { System.out.println("\t+ Collection: " + colName); } } catch (Exception e) { e.printStackTrace(); } } }
One Tiny Formatting Note
Your existing code has a typo in the collection print line: " + Collection: "+colName should be "\t+ Collection: "+colName (proper tab escape sequence). This won’t fix the missing collections, but it’ll make your output look cleaner once they appear.
Give these fixes a shot—authentication or upgrading the driver are the most likely solutions here!
内容的提问来源于stack exchange,提问作者CamMoore

