还有另一种方法可以连接针对 admin 数据库的身份验证。
缺点是您必须设置整个连接对象,而不是仅将所有信息打包在连接字符串上。
而不是使用像这样的连接字符串来实例化 MongoClient
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
您可以创建一个 MongoClientSettings 对象,设置凭据(以及任何其他连接设置)并实例化传递该对象的客户端
string authenticationDB = "admin"
string authenticationUsername = "user"
string authenticationPassword = "pass"
MongoClientSettings settings = new MongoClientSettings();
settings.Credentials = new[] { MongoCredential.CreateMongoCRCredential(authenticationDB, authenticationUsername, authenticationPassword) };
settings.Servers = new[] { new MongoServerAddress("host_1"), new MongoServerAddress("host_2"), new MongoServerAddress("host_3") };
settings.ConnectionMode = ConnectionMode.ReplicaSet;
var client = new MongoClient(settings);
var db = client.GetServer().GetDatabase(database);
http://docs.mongodb.org/ecosystem/tutorial/authenticate-with-csharp-driver/