com.mongodb.MongoQueryException: Query failed with error code 13 and error message 'command find requires authentication'
如何在java中使用密码创建mongo客户端。
我知道有这样的方法:
public MongoClient(final ServerAddress addr, final List<MongoCredential> credentialsList);
但它显示为已弃用,还有另一种方法需要 MongoClientOptions:
public MongoClient(final ServerAddress addr, final MongoCredential credential, final MongoClientOptions options)
但我没有任何发送选项。那么,有什么方法可以使用密码在java中创建mongo客户端吗?
最佳答案
要执行 find 命令,您需要先通过 mongo 进行身份验证。 如何进行身份验证的示例:
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("testdb");
boolean auth = db.authenticate("testdb", "password".toCharArray());
if (auth) {
DBCollection table = db.getCollection("user");
BasicDBObject document = new BasicDBObject();
document.put("name", "mkyong");
table.insert(document);
System.out.println("Login is successful!");
} else {
System.out.println("Login is failed!");
}
这应该适合你。
您可以查看本文中的示例代码:https://www.mkyong.com/mongodb/java-authentication-access-to-mongodb/
当使用 mongo-java-driver 时,以下内容是合适的: - 请注意,这不再使用已弃用的方法,而是将 writeconcern 设置为 Journaled(推荐)
String username = "test";
String database = "something";
String password = "secret";
MongoCredential mongoCredential = MongoCredential.createCredential(username, database, password.toCharArray());
MongoClientOptions options = MongoClientOptions.builder()
.writeConcern(WriteConcern.JOURNALED).build();
MongoClient mongoClient = new MongoClient(new ServerAddress("host1", 27017), Arrays.asList(mongoCredential), options);
关于JAVA com.mongodb.MongoQueryException : Query failed with error code 13 and error message 'command find requires authentication' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54860650/