连接到Mongo DB时发生异常:

以下是堆栈跟踪:

Exception in thread "main" com.mongodb.CommandFailureException: { "serverUsed" : "127.0.0.1:27017" , "ok" : 0.0 , "code" : 18 , "errmsg" : "Authentication failed."}
    at com.mongodb.CommandResult.getException(CommandResult.java:76)
    at com.mongodb.CommandResult.throwOnError(CommandResult.java:140)
    at com.mongodb.DBPort$SaslAuthenticator.authenticate(DBPort.java:899)
    at com.mongodb.DBPort.authenticate(DBPort.java:432)
    at com.mongodb.DBPort.checkAuth(DBPort.java:443)
    at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:293)
    at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:273)
    at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:84)
    at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:66)
    at com.mongodb.DBCursor._check(DBCursor.java:498)
    at com.mongodb.DBCursor._hasNext(DBCursor.java:621)
    at com.mongodb.DBCursor.hasNext(DBCursor.java:657)
    at mongoOperations.mongoOperations.getConnectionMongo(mongoOperations.java:103)
    at mongoOperations.mongoOperations.main(mongoOperations.java:138)


以下是代码段:

private static void getConnectionMongo(){

    try{
        String uri = "mongodb://accountUser:[email protected]/test";
        MongoClientURI mongoClientURI = new MongoClientURI(uri);
        MongoURI mongoURI = new MongoURI(mongoClientURI);
        Mongo mongo = new Mongo(mongoURI);
        UserCredentials userCredentials = new UserCredentials("accountUser", "password");
        SimpleMongoDbFactory dbFactory =  new SimpleMongoDbFactory(mongo, "test", userCredentials);
        MongoTemplate mongoTemplate = new MongoTemplate(dbFactory);
        DBCollection collection = mongoTemplate.getCollection("table");
        DBCursor cursor =  collection.find();
        while(cursor.hasNext()){
            System.out.println(cursor.next());
        }
    }
    catch(UnknownHostException e){

    }
}


以下是mongo Shell的代码段:


  db.auth('accountUser','password');
  1个


这些是使用的jar文件:
spring-data-mongodb-1.3.0.RELEASE,
mongo-java-driver-2.13.2

任何建议都是可取的。谢谢 !!

最佳答案

要么通过这个URI

String uri = "mongodb://accountUser:[email protected]/test";


或将userCredentials传递给构造函数都不能一起使用,仍然可以突出显示哪一行会引发错误


MongoTemplate mongoTemplate = new MongoTemplate(dbFactory);
DBCollection collection = mongoTemplate.getCollection("table");
DBCursor cursor = collection.find();

10-06 14:12