/// <summary> /// 数据访问助手类 //https://mongolab.com/login/ 远程MongoDb免费数据库 /// </summary> public class MongoHelper : IDisposable { private MongoServer mongoServer = null; private MongoDatabase mongoDatabase = null; private readonly static string connectionString = "mongodb://fn2008:123456@127.0.0.1:41338/iclound";//"mongodb://steven9701:fn2008@ds041337.mongolab.com:41337/ertn2012"; private readonly static string databaseName = "iclound";//admin:admin fn2008 权限
~MongoHelper() { Dispose (); }
public MongoHelper() { if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentNullException("connectionString"); }
//var settings = new MongoServerSettings //{ // Server = new MongoServerAddress("127.0.0.1", 41338), // MaxConnectionPoolSize = 1000, //};
//建立连接 mongoServer = MongoServer.Create(connectionString); mongoServer.Connect();
if (string.IsNullOrEmpty(databaseName) == false) { //取得指定Database mongoDatabase = mongoServer.GetDatabase(databaseName); } }
/// <summary> /// 切换到指定的数据库 /// </summary> /// <param name="dbName"></param> /// <returns></returns> public MongoDatabase ResetDatabase(string dbName) { if (string.IsNullOrEmpty(dbName)) { throw new ArgumentNullException(dbName); }
mongoDatabase = mongoServer.GetDatabase(dbName); return mongoDatabase; }
/// <summary> /// 获取当前连接的数据库 /// </summary> public MongoDatabase MongoDatabase { get { if (mongoDatabase == null) { throw new Exception("当前连接没有指定任何数据库。请在构造函数中指定数据库名或者调用ResetDatabase()方法切换数据库。"); }
return mongoDatabase; } }
/// <summary> /// 获取当前连接数据库的指定集合 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public MongoCollection<T> GetCollection<T>(string collectionName) where T : class { return this.MongoDatabase.GetCollection<T>(collectionName); }
/// <summary> /// 获取当前连接数据库的指定集合 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public MongoCollection<T> GetCollection<T>(string collectionName,SafeMode safeMode) where T : class { return this.MongoDatabase.GetCollection<T>(collectionName, safeMode); }
/// <summary> /// 获取当前连接数据库的指定集合 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public MongoCollection<T> GetCollection<T>(MongoCollectionSettings<T> mongoCollectionSettings) where T : class { return this.MongoDatabase.GetCollection<T>(mongoCollectionSettings); }
public void Dispose() { if (mongoServer != null) { mongoServer = null; } } }