業精於勤,荒於嬉;行成於思,毀於隨。html
咱們能夠結合相關的IDE作一個簡單的增刪改查了,實現MongoDB在項目中的初步應用。git
前提是安裝了MongoDB服務和MongoDB可視化工具,沒有安裝的能夠點下面的路徑去操做一下。mongodb
第一步:NoSql非關係型數據庫之MongoDB應用(一):安裝MongoDB服務數據庫
第二步:NoSql非關係型數據庫之MongoDB應用(二):安裝MongoDB可視化工具json
注:文檔末尾附源碼api
演示操做環境(其餘環境也能夠):數組
開發環境:Windows 10 專業版微信
系統類型:64 位操做系統, 基於 x64 的處理器網絡
IDE:Visual Studio 2019 Communityless
數據庫:MongoDB
建立一個項目名爲MongoDBTest的Web API,net或者net core均可以,我這裏以net core爲例
須要在項目中引用 MongoDB.Bson 和 MongoDB.Driver 注意是2.10.4版本的。
MongoDB.Bson是什麼
BSON是一種類json的一種二進制形式的存儲格式,簡稱Binary JSON,它和JSON同樣,支持內嵌的文檔對象和數組對象,可是BSON有JSON沒有的一些數據類型,如Date和BinData類型。
BSON能夠作爲網絡數據交換的一種存儲形式,這個有點相似於Google的Protocol Buffer,可是BSON是一種schema-less的存儲形式,它的優勢是靈活性高,但它的缺點是空間利用率不是很理想,
BSON有三個特色:輕量性、可遍歷性、高效性
{「hello":"world"} 這是一個BSON的例子,其中"hello"是key name,它通常是cstring類型,字節表示是cstring::= (byte*) "/x00" ,其中*表示零個或多個byte字節,/x00表示結束符;後面的"world"是value值,它的類型通常是string,double,array,binarydata等類型。
MongoDB.Bson在MongoDB中的使用
MongoDB使用了BSON這種結構來存儲數據和網絡數據交換。把這種格式轉化成一文檔這個概念(Document),由於BSON是schema-free的,
因此在MongoDB中所對應的文檔也有這個特徵,這裏的一個Document也能夠理解成關係數據庫中的一條記錄(Record),只是這裏的Document的變化更豐富一些,如Document能夠嵌套。
MongoDB以BSON作爲其存儲結構的一種重要緣由是其可遍歷性。
MongoDB.Driver是什麼
顧名思義,MongoDB.Driver是官網推出的鏈接MongoDB的驅動包,咱們鏈接MongoDB須要依賴這個連接庫。
引入 MongoDB.Bson 和 MongoDB.Driver包後就能夠編寫幫助類了,幫助類太多,幫助類能夠本身拓展須要的方法,不過這裏拓展的方法已經足夠使用了。
建立一個上下文文件夾DbContexts,建立DBFactory幫助類,添加Bson和Driver的using引用,內容以下(文檔末尾附源碼裏面有):
using MongoDB.Bson; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MongoDBTest.DbContexts { /// <summary> /// Date 2021-07-12 /// Author:xiongze /// Describe:MongoDB工具類 /// </summary> /// <typeparam name="T"></typeparam> 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) { var mongoSettings = MongoClientSettings.FromConnectionString(host.Connection); mongoSettings.GuidRepresentation = GuidRepresentation.PythonLegacy; MongoClient client = new MongoClient(mongoSettings); var dataBase = client.GetDatabase(host.DataBase); return dataBase.GetCollection<T>(host.Table); } #endregion } public class MongodbHost { //public MongodbHost() //{ // //Connection = CommonConfig.GetConnectionStrings().ConnectionStrings.MongoDBConnection; // Connection =""; //這裏是獲取配置鏈接的mongodb鏈接,我這裏先不指定,各類指定寫法不同(net和netcore獲取不同) // DataBase = new MongoUrl(Connection).DatabaseName; //} public MongodbHost(string connectionString) { Connection = connectionString; DataBase = new MongoUrl(connectionString).DatabaseName; } /// <summary> /// 鏈接字符串 /// </summary> public string Connection { get; set; } /// <summary> /// 庫 /// </summary> public string DataBase { get; set; } /// <summary> /// 表 /// </summary> public string Table { get; set; } } 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) { //throw 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 (Exception) { return 0; } } public static async Task<int> AsyncInsertManyMethod(MongodbHost mongodb, T log) { int i = await TMongodbHelper<T>.InsertManyAsync(mongodb, new List<T> { log }); return i; } #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.CountDocuments(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.CountDocumentsAsync(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.CountDocuments(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 #region Save 替換原數據表列 (字段刪除添加) public static T Save(MongodbHost host, FilterDefinition<T> filter, T t) { try { var client = MongodbClient<T>.MongodbInfoClient(host); return client.FindOneAndReplace(filter, t); } catch (Exception ex) { throw ex; } } #endregion #region SaveAsync 替換原數據表列 (字段刪除添加) public static async Task<T> SaveAsync(MongodbHost host, FilterDefinition<T> filter, T t) { try { var client = MongodbClient<T>.MongodbInfoClient(host); return await client.FindOneAndReplaceAsync(filter, t); } catch (Exception ex) { throw ex; } } #endregion } }
寫好工具類咱們就能夠直接寫增刪改查了。
先定義實體類,下面就不在重複說定義實體了。
[BsonIgnoreExtraElements] //忽略增長項(MongoDB是文檔型數據庫,因此數據字段是根據傳入的數據自動增長的,若是不忽略,增長項,查詢返回實體就少了字段報錯,固然也能夠查詢指定字段) public class empty_collection { public ObjectId _id { get; set; } //主鍵 public string Name { get; set; } //姓名 public List<ClassTable> ClassTable { get; set; } //數據集合 public DateTime CreateDate { get; set; } //建立時間 } public class ClassTable { public string ItemName { get; set; } //鍵名 public string ItemValue { get; set; } //值 } //返回類型實體 public class ResultInfo { public int code { get; set; } public string message { get; set; } public object result { get; set; } }
編寫插入方法,注意看裏面的註釋,數據庫鏈接的字符串格式、傳值的類型等都有詳細註釋,這裏就不進行囉嗦,直接上菜。
//插入 //GET api/values/InsertDate [HttpGet("InsertDate")] public JsonResult InsertDate() { ResultInfo res = new ResultInfo(); try { //鏈接mongodb的固定格式,應該寫在配置裏面,因爲這裏作演示,因此單獨寫 //user:user 第一個是用戶名,第二個是密碼 //localhost:27017 是你數據庫的鏈接 //TestData 是你的數據庫名稱 var mongodbClient = "mongodb://user:user@localhost:27017/TestData"; MongodbHost mongodb = new MongodbHost(mongodbClient); mongodb.DataBase = "TestData"; //數據庫名 mongodb.Table = "empty_collection"; //操做的數據表(若是數據庫沒有定義表名,插入時會自動定義) List<ClassTable> ctList = new List<ClassTable>(); int i = 0; while(i<3) { ClassTable ct = new ClassTable(); switch (i) { case 0: ct.ItemName = "班級"; ct.ItemValue = "取經天團"; break; case 1: ct.ItemName = "種族"; ct.ItemValue = "龍族"; break; case 2: ct.ItemName = "戰鬥力"; ct.ItemValue = "999999"; break; } ctList.Add(ct); i++; } empty_collection model = new empty_collection() { Name = "白龍馬", ClassTable = ctList, CreateDate=DateTime.Now }; List<empty_collection> Listmodel = new List<empty_collection>(); Listmodel.Add(model); var resCount=TMongodbHelper<empty_collection>.InsertMany(mongodb, Listmodel); // 插入多條數據 res.code = resCount; res.message = resCount > 0 ? "操做成功" : "操做失敗"; } catch (Exception ex) { res.code = -2; res.message = "操做失敗:" + ex.Message; } return new JsonResult(res); }
而後咱們運行調用這個方法,查看一下數據庫的值,很顯然寫入成功了。
編寫查詢方法,而後調用這個方法。
//查詢 //GET api/values/GetDateList [HttpGet("GetDateList")] public JsonResult GetDateList() { ResultInfo res = new ResultInfo(); try { //鏈接mongodb的固定格式,應該寫在配置裏面,因爲這裏作演示,因此單獨寫 //user:user 第一個是用戶名,第二個是密碼 //localhost:27017 是你數據庫的鏈接 //TestData 是你的數據庫名稱 var mongodbClient = "mongodb://user:user@localhost:27017/TestData"; MongodbHost mongodb = new MongodbHost(mongodbClient); mongodb.DataBase = "TestData"; //數據庫名 mongodb.Table = "empty_collection"; //操做的數據表 #region 篩選條件(至少一個條件) var list = new List<FilterDefinition<empty_collection>>(); //Gte 大於等於 Lte 小於等於 list.Add(Builders<empty_collection>.Filter.Gte("CreateDate", "2021-01-01")); //注意:MongoDB當前方法查詢須要必傳至少一個參數,不然會報錯 var filter = Builders<empty_collection>.Filter.And(list); #endregion var GetList = TMongodbHelper<empty_collection>.FindList(mongodb, filter).ToList(); //查詢所有 //var GetList = TMongodbHelper<empty_collection>.FindListByPage(mongodb, filter, 1, 5, out count).ToList(); //分頁查詢 res.code = 0; res.message = "查詢成功"; res.result = GetList; } catch (Exception ex) { res.code = -2; res.message = ex.Message; } return new JsonResult(res); }
須要注意的是,查詢語句的數據庫交互至少有一個條件
編寫修改方法,而後調用這個方法。
//修改 //GET api/values/UpdateDate [HttpGet("UpdateDate")] public JsonResult UpdateDate() { ResultInfo res = new ResultInfo(); try { //鏈接mongodb的固定格式,應該寫在配置裏面,因爲這裏作演示,因此單獨寫 //user:user 第一個是用戶名,第二個是密碼 //localhost:27017 是你數據庫的鏈接 //TestData 是你的數據庫名稱 var mongodbClient = "mongodb://user:user@localhost:27017/TestData"; MongodbHost mongodb = new MongodbHost(mongodbClient); mongodb.DataBase = "TestData"; //數據庫名 mongodb.Table = "empty_collection"; //操做的數據表 //須要修改的條件 var UpdateList = new List<FilterDefinition<empty_collection>>(); UpdateList.Add(Builders<empty_collection>.Filter.Gte("CreateDate", "2021-01-01")); //注意:MongoDB當前方法查詢須要必傳至少一個參數,不然會報錯 UpdateList.Add(Builders<empty_collection>.Filter.Eq("Name", "白龍馬")); var filterList = Builders<empty_collection>.Filter.And(UpdateList); //須要修改後的值 Dictionary<string, string> dicList = new Dictionary<string, string>(); dicList.Add("Name", "南無八部天龍廣力菩薩"); dicList.Add("CreateDate", DateTime.Now.ToString()); var resCount = TMongodbHelper<empty_collection>.UpdateManay(mongodb, dicList, filterList); res.code = resCount.ModifiedCount > 0 ? 0 : -2; res.message = resCount.ModifiedCount > 0 ? "操做成功" : "操做失敗"; } catch (Exception ex) { res.message = "操做失敗:" + ex.Message; } return new JsonResult(res); }
編寫刪除方法,而後調用這個方法。
//刪除 //GET api/values/DeleteDate [HttpGet("DeleteDate")] public JsonResult DeleteDate() { ResultInfo res = new ResultInfo(); try { //鏈接mongodb的固定格式,應該寫在配置裏面,因爲這裏作演示,因此單獨寫 //user:user 第一個是用戶名,第二個是密碼 //localhost:27017 是你數據庫的鏈接 //TestData 是你的數據庫名稱 var mongodbClient = "mongodb://user:user@localhost:27017/TestData"; MongodbHost mongodb = new MongodbHost(mongodbClient); mongodb.DataBase = "TestData"; //數據庫名 mongodb.Table = "empty_collection"; //操做的數據表 #region 篩選條件(至少一個條件) var list = new List<FilterDefinition<empty_collection>>(); //Gte 大於等於 Lte 小於等於 list.Add(Builders<empty_collection>.Filter.Gte("CreateDate", "2021-01-01")); //注意:MongoDB當前方法查詢須要必傳至少一個參數,不然會報錯 list.Add(Builders<empty_collection>.Filter.Eq("Name", "南無八部天龍廣力菩薩")); var filter = Builders<empty_collection>.Filter.And(list); #endregion var resCount = TMongodbHelper<empty_collection>.DeleteMany(mongodb, filter); res.code = resCount.DeletedCount > 0 ? 0 : -2; res.message = resCount.DeletedCount > 0 ? "操做成功" : "操做失敗"; } catch (Exception ex) { res.message = "操做失敗:" + ex.Message; } return new JsonResult(res); }
https://gitee.com/xiongze/MongoDBTest.git
https://gitee.com/xiongze/MongoDBTest
NoSql非關係型數據庫之MongoDB在項目中的初步應用咱們就介紹到這裏了,
有想法其餘想法的能夠在評論區留言討論。
歡迎關注訂閱微信公衆號【熊澤有話說】,更多好玩易學知識等你來取
做者:熊澤-學習中的苦與樂 公衆號:熊澤有話說 出處:https://www.cnblogs.com/xiongze520/p/15001789.html 創做不易,任何人或團體、機構所有轉載或者部分轉載、摘錄,請在文章明顯位置註明做者和原文連接。
|