JAVA com.mongodb.MongoQueryException : Query failed with error code 13 and error message 'command find requires authentication'

标签 java mongodb mongo-java-driver

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/

相关文章:

java - Selenium 无法通过 moveToElement 在 IE 中单击正确的目标,但可以在 Chrome 中使用

java - 如何通过java调用sharepoint 2007 webservices?

java - Spring MongoTemplate - 将聚合结果映射到集合(例如 List 和 Map)

java - Mongo java 驱动程序表示 PojoCodec 不支持具有泛型类型的顶级类

java - 从可执行jar创建可执行文件时如何添加依赖库?

javascript - Mongo/Mongoose - markModified 不起作用

javascript - mongodb中如何加入集合

java - 无法在java中通过JNDI连接MongoDb

mongodb - 如何在 java/scala 中使用 inc 运算符创建 Decimal128 字段

java - 如果 avro 模式与数据一起存储,为什么 java avro api 需要我提供模式文件?