我正在编写Java代码,以使用带有MongoRepository的Spring Boot在MongoDB中的集合中进行简单搜索。我收到以下错误:
com.mongodb.MongoQueryException: Query failed with error code 13 and error message 'not authorized on PatientStore to execute command { find: "patientEpisode", filter: { _id: "125903_57aa8715217063663d56b1fb" }, limit: 1, singleBatch: true }' on server db-mongodev.orgname.local:27017
但是,我可以使用相同的用户密码从Robo3t执行以下查询。
db.patientEpisode.find({_id : "125903_57a3782afc1ce5ab030f7535"}).limit(1);
以下是我连接到MongoDB的方式。
@Bean
public MongoDbFactory mongoDbFactory(){
MongoRepository mongoRepository = new MongoRepository("PatientStore");
logger.info("printing values again: {}",mongoRepository.getUsernameMongo());
logger.info("mongoDatabase {}",mongoDatabase);
logger.info("mongoRepository.getPasswordMongo().toCharArray():{}",mongoRepository.getPasswordMongo().toCharArray());
// MongoCredential credential = MongoCredential.createCredential(mongoRepository.getUsernameMongo(),
// mongoDatabase,mongoRepository.getPasswordMongo().toCharArray());
// MongoCredential credential = MongoCredential.createScramSha1Credential(mongoRepository.getUsernameMongo(),mongoDatabase,mongoRepository.getPasswordMongo().toCharArray());
/*
MongoCredential credential = MongoCredential.createScramSha1Credential("user1","patientstore","password1".toCharArray());
*/
MongoClientURI clientURI = new MongoClientURI("mongodb://user1:password1@db-mongodev.orgname" +
".local:27017/patientstore" +
"?authMechanism=SCRAM-SHA-1");
MongoClient mongoClient = (MongoClient)Mongo.Holder.singleton().connect(clientURI);
/*
MongoClient mongoClient = new MongoClient(new ServerAddress(mongoHost,mongoPort),credential,
MongoClientOptions.builder().writeConcern(WriteConcern.W1.withJournal(true)).build());
*/
return new SimpleMongoDbFactory(mongoClient,"PatientStore");
}
如您所见,我同时使用MongoURI
和MongoCredential
API来创建连接,但是在两种情况下,我都遇到相同的错误。可能是什么原因?