无法从java驱动程序连接到MongoLab

时间:2016-12-27 07:11:15

标签: mongodb mlab mongo-java-driver

我有Mongolab帐户,该帐户中只有一个用户。

我可以使用MongoChef工具连接到数据库,但是当我尝试使用java驱动程序3.2.0从Eclipse中连接到该数据库时,我不断获得身份验证失败。我收到以下错误。我在Java 7上。

修改 用于连接MongoLab托管的MongoDB实例的Java代码。

    String mongoURL = new StringBuilder().append("mongodb://").append(mongoUserName).append(":").append(mongoPassword).append("@").append(mongoServer).append(":").append(mongoPort).append("/").append(dbName).toString();
    System.out.println(" The Mongo URL is " +mongoURL);
    MongoClientURI uri = new MongoClientURI(mongoURL);
    MongoClient mongo = new MongoClient(uri);

尝试连接时收到异常。

 com.mongodb.MongoTimeoutException: Timed out after 30000 ms while
 waiting for a server that matches
 ReadPreferenceServerSelector{readPreference=primary}. Client view of
 cluster state is {type=UNKNOWN,
 servers=[{address=ds061974.mongolab.com:61974, type=UNKNOWN,
 state=CONNECTING, exception={com.mongodb.MongoSecurityException:
 Exception authenticating MongoCredential{mechanism=null,
 userName='xxxx', source='hidden', password=<hidden>,
 mechanismProperties={}}}, caused by
 {com.mongodb.MongoCommandException: Command failed with error 18:
 'Authentication failed.' on server ds061974.mongolab.com:61974. The
 full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication
 failed." }}}]

1 个答案:

答案 0 :(得分:0)

试试这段代码:

ServerAddress addr = new ServerAddress(mongoServer, mongoPort);
MongoCredential credential = MongoCredential.createMongoCredential(
        mongoUserName, mongoPassword, dbName);

MongoClient mongoClient = new MongoClient(addr, Arrays.asList(credential), null);