一:引用的mongodb驅動文件版本爲 Mongodb.Driver 20.4.3html
二:我只是進行了經常使用方法的封裝,若有不當之處,請聯繫我mongodb
建立mongodb的鏈接異步
using MongoDB.Bson; using MongoDB.Driver; namespace MongodbTest.Comon { public static class MongodbClient<T> where T : class { #region +MongodbInfoClient 獲取mongodb實例 /// <summary> /// 獲取mongodb實例 /// </summary> /// <param name="host">鏈接字符串,庫,表</param> /// <returns></returns> public static IMongoCollection<T> MongodbInfoClient(MongodbHost host) { MongoClient client = new MongoClient(host.Connection); var dataBase = client.GetDatabase(host.DataBase); return dataBase.GetCollection<T>(host.Table); } #endregion } public class MongodbHost { /// <summary> /// 鏈接字符串 /// </summary> public string Connection { get; set; } /// <summary> /// 庫 /// </summary> public string DataBase { get; set; } /// <summary> /// 表 /// </summary> public string Table { get; set; } } }
三:mongodb的增刪改查async
public static class TMongodbHelper<T> where T : class, new() { #region +Add 添加一條數據 /// <summary> /// 添加一條數據 /// </summary> /// <param name="t">添加的實體</param> /// <param name="host">mongodb鏈接信息</param> /// <returns></returns> public static int Add(MongodbHost host, T t) { try { var client = MongodbClient<T>.MongodbInfoClient(host); client.InsertOne(t); return 1; } catch { return 0; } } #endregion #region +AddAsync 異步添加一條數據 /// <summary> /// 異步添加一條數據 /// </summary> /// <param name="t">添加的實體</param> /// <param name="host">mongodb鏈接信息</param> /// <returns></returns> public static async Task<int> AddAsync(MongodbHost host, T t) { try { var client = MongodbClient<T>.MongodbInfoClient(host); await client.InsertOneAsync(t); return 1; } catch { return 0; } } #endregion #region +InsertMany 批量插入 /// <summary> /// 批量插入 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="t">實體集合</param> /// <returns></returns> public static int InsertMany(MongodbHost host, List<T> t) { try { var client = MongodbClient<T>.MongodbInfoClient(host); client.InsertMany(t); return 1; } catch (Exception ex) { return 0; } } #endregion #region +InsertManyAsync 異步批量插入 /// <summary> /// 異步批量插入 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="t">實體集合</param> /// <returns></returns> public static async Task<int> InsertManyAsync(MongodbHost host, List<T> t) { try { var client = MongodbClient<T>.MongodbInfoClient(host); await client.InsertManyAsync(t); return 1; } catch { return 0; } } #endregion #region +Update 修改一條數據 /// <summary> /// 修改一條數據 /// </summary> /// <param name="t">添加的實體</param> /// <param name="host">mongodb鏈接信息</param> /// <returns></returns> public static UpdateResult Update(MongodbHost host, T t, string id) { try { var client = MongodbClient<T>.MongodbInfoClient(host); //修改條件 FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id)); //要修改的字段 var list = new List<UpdateDefinition<T>>(); foreach (var item in t.GetType().GetProperties()) { if (item.Name.ToLower() == "id") continue; list.Add(Builders<T>.Update.Set(item.Name, item.GetValue(t))); } var updatefilter = Builders<T>.Update.Combine(list); return client.UpdateOne(filter, updatefilter); } catch (Exception ex) { throw ex; } } #endregion #region +UpdateAsync 異步修改一條數據 /// <summary> /// 異步修改一條數據 /// </summary> /// <param name="t">添加的實體</param> /// <param name="host">mongodb鏈接信息</param> /// <returns></returns> public static async Task<UpdateResult> UpdateAsync(MongodbHost host, T t, string id) { try { var client = MongodbClient<T>.MongodbInfoClient(host); //修改條件 FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id)); //要修改的字段 var list = new List<UpdateDefinition<T>>(); foreach (var item in t.GetType().GetProperties()) { if (item.Name.ToLower() == "id") continue; list.Add(Builders<T>.Update.Set(item.Name, item.GetValue(t))); } var updatefilter = Builders<T>.Update.Combine(list); return await client.UpdateOneAsync(filter, updatefilter); } catch (Exception ex) { throw ex; } } #endregion #region +UpdateManay 批量修改數據 /// <summary> /// 批量修改數據 /// </summary> /// <param name="dic">要修改的字段</param> /// <param name="host">mongodb鏈接信息</param> /// <param name="filter">修改條件</param> /// <returns></returns> public static UpdateResult UpdateManay(MongodbHost host, Dictionary<string, string> dic, FilterDefinition<T> filter) { try { var client = MongodbClient<T>.MongodbInfoClient(host); T t = new T(); //要修改的字段 var list = new List<UpdateDefinition<T>>(); foreach (var item in t.GetType().GetProperties()) { if (!dic.ContainsKey(item.Name)) continue; var value = dic[item.Name]; list.Add(Builders<T>.Update.Set(item.Name, value)); } var updatefilter = Builders<T>.Update.Combine(list); return client.UpdateMany(filter, updatefilter); } catch (Exception ex) { throw ex; } } #endregion #region +UpdateManayAsync 異步批量修改數據 /// <summary> /// 異步批量修改數據 /// </summary> /// <param name="dic">要修改的字段</param> /// <param name="host">mongodb鏈接信息</param> /// <param name="filter">修改條件</param> /// <returns></returns> public static async Task<UpdateResult> UpdateManayAsync(MongodbHost host, Dictionary<string, string> dic, FilterDefinition<T> filter) { try { var client = MongodbClient<T>.MongodbInfoClient(host); T t = new T(); //要修改的字段 var list = new List<UpdateDefinition<T>>(); foreach (var item in t.GetType().GetProperties()) { if (!dic.ContainsKey(item.Name)) continue; var value = dic[item.Name]; list.Add(Builders<T>.Update.Set(item.Name, value)); } var updatefilter = Builders<T>.Update.Combine(list); return await client.UpdateManyAsync(filter, updatefilter); } catch (Exception ex) { throw ex; } } #endregion #region Delete 刪除一條數據 /// <summary> /// 刪除一條數據 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="id">objectId</param> /// <returns></returns> public static DeleteResult Delete(MongodbHost host, string id) { try { var client = MongodbClient<T>.MongodbInfoClient(host); FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id)); return client.DeleteOne(filter); } catch (Exception ex) { throw ex; } } #endregion #region DeleteAsync 異步刪除一條數據 /// <summary> /// 異步刪除一條數據 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="id">objectId</param> /// <returns></returns> public static async Task<DeleteResult> DeleteAsync(MongodbHost host, string id) { try { var client = MongodbClient<T>.MongodbInfoClient(host); //修改條件 FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id)); return await client.DeleteOneAsync(filter); } catch (Exception ex) { throw ex; } } #endregion #region DeleteMany 刪除多條數據 /// <summary> /// 刪除一條數據 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="filter">刪除的條件</param> /// <returns></returns> public static DeleteResult DeleteMany(MongodbHost host, FilterDefinition<T> filter) { try { var client = MongodbClient<T>.MongodbInfoClient(host); return client.DeleteMany(filter); } catch (Exception ex) { throw ex; } } #endregion #region DeleteManyAsync 異步刪除多條數據 /// <summary> /// 異步刪除多條數據 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="filter">刪除的條件</param> /// <returns></returns> public static async Task<DeleteResult> DeleteManyAsync(MongodbHost host, FilterDefinition<T> filter) { try { var client = MongodbClient<T>.MongodbInfoClient(host); return await client.DeleteManyAsync(filter); } catch (Exception ex) { throw ex; } } #endregion #region Count 根據條件獲取總數 /// <summary> /// 根據條件獲取總數 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="filter">條件</param> /// <returns></returns> public static long Count(MongodbHost host, FilterDefinition<T> filter) { try { var client = MongodbClient<T>.MongodbInfoClient(host); return client.Count(filter); } catch (Exception ex) { throw ex; } } #endregion #region CountAsync 異步根據條件獲取總數 /// <summary> /// 異步根據條件獲取總數 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="filter">條件</param> /// <returns></returns> public static async Task<long> CountAsync(MongodbHost host, FilterDefinition<T> filter) { try { var client = MongodbClient<T>.MongodbInfoClient(host); return await client.CountAsync(filter); } catch (Exception ex) { throw ex; } } #endregion #region FindOne 根據id查詢一條數據 /// <summary> /// 根據id查詢一條數據 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="id">objectid</param> /// <param name="field">要查詢的字段,不寫時查詢所有</param> /// <returns></returns> public static T FindOne(MongodbHost host, string id, string[] field = null) { try { var client = MongodbClient<T>.MongodbInfoClient(host); FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id)); //不指定查詢字段 if (field == null || field.Length == 0) { return client.Find(filter).FirstOrDefault<T>(); } //制定查詢字段 var fieldList = new List<ProjectionDefinition<T>>(); for (int i = 0; i < field.Length; i++) { fieldList.Add(Builders<T>.Projection.Include(field[i].ToString())); } var projection = Builders<T>.Projection.Combine(fieldList); fieldList?.Clear(); return client.Find(filter).Project<T>(projection).FirstOrDefault<T>(); } catch (Exception ex) { throw ex; } } #endregion #region FindOneAsync 異步根據id查詢一條數據 /// <summary> /// 異步根據id查詢一條數據 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="id">objectid</param> /// <returns></returns> public static async Task<T> FindOneAsync(MongodbHost host, string id, string[] field = null) { try { var client = MongodbClient<T>.MongodbInfoClient(host); FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id)); //不指定查詢字段 if (field == null || field.Length == 0) { return await client.Find(filter).FirstOrDefaultAsync(); } //制定查詢字段 var fieldList = new List<ProjectionDefinition<T>>(); for (int i = 0; i < field.Length; i++) { fieldList.Add(Builders<T>.Projection.Include(field[i].ToString())); } var projection = Builders<T>.Projection.Combine(fieldList); fieldList?.Clear(); return await client.Find(filter).Project<T>(projection).FirstOrDefaultAsync(); } catch (Exception ex) { throw ex; } } #endregion #region FindList 查詢集合 /// <summary> /// 查詢集合 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="filter">查詢條件</param> /// <param name="field">要查詢的字段,不寫時查詢所有</param> /// <param name="sort">要排序的字段</param> /// <returns></returns> public static List<T> FindList(MongodbHost host, FilterDefinition<T> filter, string[] field = null, SortDefinition<T> sort = null) { try { var client = MongodbClient<T>.MongodbInfoClient(host); //不指定查詢字段 if (field == null || field.Length == 0) { if (sort == null) return client.Find(filter).ToList(); //進行排序 return client.Find(filter).Sort(sort).ToList(); } //制定查詢字段 var fieldList = new List<ProjectionDefinition<T>>(); for (int i = 0; i < field.Length; i++) { fieldList.Add(Builders<T>.Projection.Include(field[i].ToString())); } var projection = Builders<T>.Projection.Combine(fieldList); fieldList?.Clear(); if (sort == null) return client.Find(filter).Project<T>(projection).ToList(); //排序查詢 return client.Find(filter).Sort(sort).Project<T>(projection).ToList(); } catch (Exception ex) { throw ex; } } #endregion #region FindListAsync 異步查詢集合 /// <summary> /// 異步查詢集合 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="filter">查詢條件</param> /// <param name="field">要查詢的字段,不寫時查詢所有</param> /// <param name="sort">要排序的字段</param> /// <returns></returns> public static async Task<List<T>> FindListAsync(MongodbHost host, FilterDefinition<T> filter, string[] field = null, SortDefinition<T> sort = null) { try { var client = MongodbClient<T>.MongodbInfoClient(host); //不指定查詢字段 if (field == null || field.Length == 0) { if (sort == null) return await client.Find(filter).ToListAsync(); return await client.Find(filter).Sort(sort).ToListAsync(); } //制定查詢字段 var fieldList = new List<ProjectionDefinition<T>>(); for (int i = 0; i < field.Length; i++) { fieldList.Add(Builders<T>.Projection.Include(field[i].ToString())); } var projection = Builders<T>.Projection.Combine(fieldList); fieldList?.Clear(); if (sort == null) return await client.Find(filter).Project<T>(projection).ToListAsync(); //排序查詢 return await client.Find(filter).Sort(sort).Project<T>(projection).ToListAsync(); } catch (Exception ex) { throw ex; } } #endregion #region FindListByPage 分頁查詢集合 /// <summary> /// 分頁查詢集合 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="filter">查詢條件</param> /// <param name="pageIndex">當前頁</param> /// <param name="pageSize">頁容量</param> /// <param name="count">總條數</param> /// <param name="field">要查詢的字段,不寫時查詢所有</param> /// <param name="sort">要排序的字段</param> /// <returns></returns> public static List<T> FindListByPage(MongodbHost host, FilterDefinition<T> filter, int pageIndex, int pageSize, out long count, string[] field = null, SortDefinition<T> sort = null) { try { var client = MongodbClient<T>.MongodbInfoClient(host); count = client.Count(filter); //不指定查詢字段 if (field == null || field.Length == 0) { if (sort == null) return client.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList(); //進行排序 return client.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList(); } //制定查詢字段 var fieldList = new List<ProjectionDefinition<T>>(); for (int i = 0; i < field.Length; i++) { fieldList.Add(Builders<T>.Projection.Include(field[i].ToString())); } var projection = Builders<T>.Projection.Combine(fieldList); fieldList?.Clear(); //不排序 if (sort == null) return client.Find(filter).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList(); //排序查詢 return client.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList(); } catch (Exception ex) { throw ex; } } #endregion #region FindListByPageAsync 異步分頁查詢集合 /// <summary> /// 異步分頁查詢集合 /// </summary> /// <param name="host">mongodb鏈接信息</param> /// <param name="filter">查詢條件</param> /// <param name="pageIndex">當前頁</param> /// <param name="pageSize">頁容量</param> /// <param name="field">要查詢的字段,不寫時查詢所有</param> /// <param name="sort">要排序的字段</param> /// <returns></returns> public static async Task<List<T>> FindListByPageAsync(MongodbHost host, FilterDefinition<T> filter, int pageIndex, int pageSize, string[] field = null, SortDefinition<T> sort = null) { try { var client = MongodbClient<T>.MongodbInfoClient(host); //不指定查詢字段 if (field == null || field.Length == 0) { if (sort == null) return await client.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); //進行排序 return await client.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); } //制定查詢字段 var fieldList = new List<ProjectionDefinition<T>>(); for (int i = 0; i < field.Length; i++) { fieldList.Add(Builders<T>.Projection.Include(field[i].ToString())); } var projection = Builders<T>.Projection.Combine(fieldList); fieldList?.Clear(); //不排序 if (sort == null) return await client.Find(filter).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); //排序查詢 return await client.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); } catch (Exception ex) { throw ex; } } #endregion }
三:調用栗子ui
//1.批量修改,修改的條件 var time = DateTime.Now; var list = new List<FilterDefinition<PhoneEntity>>(); list.Add(Builders<PhoneEntity>.Filter.Lt("AddTime", time.AddDays(5))); list.Add(Builders<PhoneEntity>.Filter.Gt("AddTime", time)); var filter = Builders<PhoneEntity>.Filter.And(list); //2.要修改的字段內容 var dic = new Dictionary<string, string>(); dic.Add("UseAge", "168"); dic.Add("Name", "朝陽"); //3.批量修改 var kk = TMongodbHelper<PhoneEntity>.UpdateManay(host, dic, filter);
//根據條件查詢集合 var time = DateTime.Now; var list = new List<FilterDefinition<PhoneEntity>>(); list.Add(Builders<PhoneEntity>.Filter.Lt("AddTime", time.AddDays(20))); list.Add(Builders<PhoneEntity>.Filter.Gt("AddTime", time)); var filter = Builders<PhoneEntity>.Filter.And(list); //2.查詢字段 var field = new[] { "Name", "Price", "AddTime" }; //3.排序字段 var sort = Builders<PhoneEntity>.Sort.Descending("AddTime"); var res = TMongodbHelper<PhoneEntity>.FindList(host, filter, field, sort);
//分頁查詢,查詢條件 var time = DateTime.Now; var list = new List<FilterDefinition<PhoneEntity>>(); list.Add(Builders<PhoneEntity>.Filter.Lt("AddTime", time.AddDays(400))); list.Add(Builders<PhoneEntity>.Filter.Gt("AddTime", time)); var filter = Builders<PhoneEntity>.Filter.And(list); long count = 0; //排序條件 var sort = Builders<PhoneEntity>.Sort.Descending("AddTime"); var res = TMongodbHelper<PhoneEntity>.FindListByPage(host, filter, 2, 10, out count, null, sort);
四,缺乏sdk文件時,請自行安裝spa
參考文章:http://www.cnblogs.com/yaozhenfa/p/4574898.htmlcode