配置文件中链接地址:mongodb://test:123456@192.168.168.186:9999/temp
读取配置文件:
/// <summary> /// 构造函数 /// </summary> /// <param name="connectionStrings"></param> public MongodbHelper(string connectionStrings) { var mongoUrl = new MongoUrlBuilder(connectionStrings); string databaseName = mongoUrl.DatabaseName; MongoClientSettings mongoSettings = new MongoClientSettings(); TimeSpan t = new TimeSpan(3000); mongoSettings.ConnectTimeout = t;//设置连接超时时长 mongoSettings.MaxConnectionPoolSize = 2000;//设置连接池最大连接数 MongoCredential credentials = MongoCredential.CreateCredential(databaseName, mongoUrl.Username, mongoUrl.Password);//添加用户名、密码 mongoSettings.Credential = credentials; mongoSettings.Server = mongoUrl.Server;//服务器地址 mongoSettings.ReadPreference = new ReadPreference(ReadPreferenceMode.Primary); MongoClient client = new MongoClient(mongoSettings); }