[英]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.