NoSql非關係型資料庫之MongoDB應用(三):MongoDB在項目中的初步應用

業精於勤,荒於嬉;行成於思,毀於隨。

 

我們可以結合相關的IDE做一個簡單的增刪改查了,實現MongoDB在項目中的初步應用。

前提是安裝了MongoDB服務和MongoDB可視化工具,沒有安裝的可以點下面的路徑去操作一下。

第一步:NoSql非關係型資料庫之MongoDB應用(一):安裝MongoDB服務

第二步:NoSql非關係型資料庫之MongoDB應用(二):安裝MongoDB可視化工具

 

註:文檔末尾附源碼


1、創建項目

演示操作環境(其他環境也可以):

開發環境:Windows 10 專業版

系統類型:64 位作業系統, 基於 x64 的處理器

IDE:Visual Studio 2019 Community

資料庫:MongoDB


創建一個項目名為MongoDBTest的Web API,net或者net core都可以,我這裡以net core為例


 

2、在NuGet引用MongoDB動態鏈接庫

需要在項目中引用 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需要依賴這個鏈接庫。


2、創建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



    }
}

View Code


寫好工具類我們就可以直接寫增刪改查了。


3、連接MongoDB編編寫語句

3.1、插入

先定義實體類,下面就不在重複說定義實體了。

 [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; }
        }

View Code

 

編寫插入方法,注意看裡面的注釋,資料庫連接的字元串格式、傳值的類型等都有詳細注釋,這裡就不進行啰嗦,直接上菜。

//插入
        //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);
        }

View Code

 

然後我們運行調用這個方法,查看一下資料庫的值,很顯然寫入成功了。

 

 


3.2、查詢

編寫查詢方法,然後調用這個方法。

 //查詢
        //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);
        }

View Code

需要注意的是,查詢語句的資料庫交互至少有一個條件


3.3、修改

編寫修改方法,然後調用這個方法。

 //修改
        //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);
        }

View Code

  


3.4、刪除

編寫刪除方法,然後調用這個方法。

//刪除
        //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);
        }

View Code

 

  


源碼下載(git)

//gitee.com/xiongze/MongoDBTest.git

//gitee.com/xiongze/MongoDBTest


後語

NoSql非關係型資料庫之MongoDB在項目中的初步應用我們就介紹到這裡了,

有想法其他想法的可以在評論區留言討論。

 

 
歡迎關注訂閱微信公眾號【熊澤有話說】,更多好玩易學知識等你來取

作者:熊澤-學習中的苦與樂

公眾號:熊澤有話說


出處://www.cnblogs.com/xiongze520/p/15001789.html



創作不易,任何人或團體、機構全部轉載或者部分轉載、摘錄,請在文章明顯位置註明作者和原文鏈接。