C#驅動對mongodb的操做,目前驅動有兩種:官方驅動和samus驅動(官方驅動比較原生態,業務擴展比較靈活;samus第三方驅動提供了豐富的linq操做,至關方便) 。mysql
官方驅動下載地址:https://github.com/mongodb/mongo-csharp-driver/downloadsgit
samus驅動下載地址:https://github.com/samus/mongodb-csharp/downloadsgithub
1、samus驅動使用示例:sql
實體類:mongodb
/// <summary> /// 數據實體 /// </summary> public class Person { [MongoAlias("_id")] public string ID { get; set; } public string Name { get; set; } public int Age { get; set; } public DateTime CreateTime { get; set; } }
Mongo數據庫操做類:數據庫
public class MongodbHelper<T> where T : class { string connectionString = string.Empty; string databaseName = string.Empty; string collectionName = string.Empty; static MongodbHelper<T> mongodb; #region 初始化操做 /// <summary> /// 初始化操做 /// </summary> public MongodbHelper() { connectionString = "Server=127.0.0.1:27017"; databaseName = "test"; collectionName = "person"; } #endregion #region 實現linq查詢的映射配置 /// <summary> /// 實現linq查詢的映射配置 /// </summary> public MongoConfiguration configuration { get { var config = new MongoConfigurationBuilder(); config.Mapping(mapping => { mapping.DefaultProfile(profile => { profile.SubClassesAre(t => t.IsSubclassOf(typeof(T))); }); mapping.Map<T>(); mapping.Map<T>(); }); config.ConnectionString(connectionString); return config.BuildConfiguration(); } } #endregion #region 插入操做 /// <summary> /// 插入操做 /// </summary> /// <param name="person"></param> /// <returns></returns> public void Insert(T t) { using (Mongo mongo = new Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection<T>(collectionName); collection.Insert(t, true); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion #region 更新操做 /// <summary> /// 更新操做 /// </summary> /// <param name="person"></param> /// <returns></returns> public void Update(T t, Expression<Func<T, bool>> func) { using (Mongo mongo = new Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection<T>(collectionName); collection.Update<T>(t, func, true); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion #region 獲取集合 /// <summary> ///獲取集合 /// </summary> /// <param name="person"></param> /// <returns></returns> public List<T> List(int pageIndex, int pageSize, Expression<Func<T, bool>> func, out int pageCount) { pageCount = 0; using (Mongo mongo = new Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection<T>(collectionName); pageCount = Convert.ToInt32(collection.Count()); var personList = collection.Linq().Where(func).Skip(pageSize * (pageIndex - 1)) .Take(pageSize).Select(i => i).ToList(); mongo.Disconnect(); return personList; } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion #region 讀取單條記錄 /// <summary> ///讀取單條記錄 /// </summary> /// <param name="person"></param> /// <returns></returns> public T Single(Expression<Func<T, bool>> func) { using (Mongo mongo = new Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection<T>(collectionName); var single = collection.Linq().FirstOrDefault(func); mongo.Disconnect(); return single; } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion #region 刪除操做 /// <summary> /// 刪除操做 /// </summary> /// <param name="person"></param> /// <returns></returns> public void Delete(Expression<Func<T, bool>> func) { using (Mongo mongo = new Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection<T>(collectionName); //這個地方要注意,必定要加上T參數,不然會看成object類型處理 //致使刪除失敗 collection.Remove<T>(func); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion }
調用操做類:c#
class Program { static void Main(string[] args) { MongodbHelper<Person> helper = new MongodbHelper<Person>(); //插入操做 for (int i = 0; i < 1000; i++) { helper.Insert(new Person() { ID = Guid.NewGuid().ToString(), Name = "jack" + i, Age = i, CreateTime = DateTime.Now }); } Console.WriteLine("插入成功"); //修改操做 var single = helper.Single(i => i.Name == "jack0"); single.Name = "mary"; helper.Update(single, i => i.ID == single.ID); Console.WriteLine("修改爲功"); //刪除操做 helper.Delete(i => i.Name == "mary"); Console.WriteLine("刪除成功"); //查詢操做 int pagecount; //獲取名字裏面帶9的人數 var list = helper.List(1, 20, i => i.Name.Contains("9"), out pagecount); Console.WriteLine("名字裏面帶9的人數:" + pagecount); Console.Read(); } }
2、官方驅動使用示例:服務器
數據庫操做類:app
class Program { static void Main(string[] args) { //MongoDB服務器鏈接串 string connectionString = "mongodb://127.0.0.1"; MongoServer server = MongoServer.Create(connectionString); //鏈接到 mongodb_c_demo 數據庫 MongoDatabase db = server.GetDatabase("test"); //獲取集合 fruit MongoCollection collection = db.GetCollection("fruit"); //建立對象 fruit_1 BsonDocument fruit_1 = new BsonDocument { { "name", "apple" }, { "color", "red" } }; //建立對象 fruit_2 BsonDocument fruit_2 = new BsonDocument { { "name", "banana" }, { "color", "yellow" } }; //將對象 fruit_1 放到集合 fruit 中 collection.Insert(fruit_1); //將對象 fruit_2 放到集合 fruit 中 collection.Insert(fruit_2); //以上代碼完成的就是向fruit表中插入2條數據,用mysql的語法解釋即 //insert into mongodb_c_demo.fruit (name, color) //values ('apple', 'red'), ('banana', 'yellow'); Console.Read(); }