[英]MongoDB raw java connection
我正在尝试创建一个通用的 mongo 连接组件,它将与不同的 mongo 数据库实例一起使用。 我设法使它与一些代码一起工作,例如:
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
System.out.println("Credentials ::"+ credential);
我不明白为什么它需要在 2 个地方指定数据库: "myDb"
,一次在凭证中,一次在它执行getDatabase
时。 不仅如此,在我的设置中,我还需要在createCredential
上指定一个不同的数据库:“admin”才能工作。 为什么凭据数据库与我将运行查询的数据库不同?
当您更深入地检查代码时,您会发现以下令人信服的原因。
这是所有验证器都崩溃的地方。
private void authenticateAll(final InternalConnection internalConnection, final ConnectionDescription connectionDescription) {
if (connectionDescription.getServerType() != ServerType.REPLICA_SET_ARBITER) {
for (final Authenticator cur : authenticators) {
cur.authenticate(internalConnection, connectionDescription);
}
}
}
authenticators
包含凭据列表。 有四种实现方式。
“myDb”,一旦在凭证中 - 为什么
此处指定的主要原因是,必须在哪个数据库上执行身份验证命令,因为每个数据库可以有不同的用户名。
executeCommand(getCredential().getSource(), authCommand, connection);
有一次它做一个 getDatabase - 为什么
这是完全不同的。 它返回MongoDatabase
object,其中包含read, write concerns, list of collections, create view, create collection
选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.