c#操作MangoDB 之MangoDB CSharp Driver驅動詳解

張龍豪發表於2015-12-16

序言

MangoDB CSharp Driver是c#操作mongodb的官方驅動。

官方Api文件:http://api.mongodb.org/csharp/2.2/html/R_Project_CSharpDriverDocs.htm#!

驅動的具體介紹:https://docs.mongodb.org/ecosystem/drivers/csharp/

本文主要對c#操作mongodb的增刪改查,以及資料庫連結配置做程式碼示例,方便進一步封裝及學習。

mongodb連結配置

 public class MongoConfig
    {       
        public static MongoServerSettings config = null;
        static MongoConfig()
        {
            config = MongoServerSettings.FromUrl(MongoUrl.Create(conStr));
            //最大連線池
            config.MaxConnectionPoolSize = 500;
            //最大閒置時間
            config.MaxConnectionIdleTime = TimeSpan.FromSeconds(30);
            //最大存活時間
            config.MaxConnectionLifeTime = TimeSpan.FromSeconds(60);
            //連結時間
            config.ConnectTimeout = TimeSpan.FromSeconds(10);
            //等待佇列大小
            config.WaitQueueSize = 50;
            //socket超時時間
            config.SocketTimeout = TimeSpan.FromSeconds(10);
            //佇列等待時間
            config.WaitQueueTimeout = TimeSpan.FromSeconds(60);
            //操作時間
            config.OperationTimeout = TimeSpan.FromSeconds(60); 
        }
        public static string conStr
        {
            get
            {
                return ConfigurationManager.AppSettings["connectionString"];
            }
        }
        public static string mongoDB
        {
            get
            {
                return ConfigurationManager.AppSettings["mongoDB"];
            }
        }
    }
public class MongoCon : IDisposable
    {
        public static MongoServer mongoCon = null;
        public static MongoDatabase mongo { get; private set; }
        private bool disposed = false;
        static MongoCon()
        {
            //建立連結
            mongoCon = new MongoServer(MongoConfig.config);
            //開啟連結
            mongoCon.Connect();
            //獲取mongodb指定資料庫
            mongo = mongoCon.GetDatabase(MongoConfig.mongoDB);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    //釋放連結
                    mongoCon.Disconnect();
                }
                mongoCon = null;
            }
            this.disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }

c#操作mongodb增刪改查詳細

 public class DoMongo
    {
        private static MongoDatabase mdb = MongoCon.mongo;
        #region 新增
        /// <summary>  
        /// 新增  
        /// </summary>   
        public static Boolean Insert(String collectionName, BsonDocument document)
        {
            MongoCollection<BsonDocument> collection = mdb.GetCollection<BsonDocument>(collectionName);
            try
            {
                collection.Insert(document);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>  
        /// 新增  
        /// </summary>   
        public static Boolean Insert<T>(String collectionName, T t)
        {
            var collection = mdb.GetCollection<T>(collectionName);
            try
            {
                collection.Insert(t);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>  
        /// 批量新增  
        /// </summary>
        public static WriteConcernResult Insert<T>(String collectionName, List<T> list)
        {
            var collection = mdb.GetCollection<T>(collectionName);
            try
            {
                return collection.Insert(list);
            }
            catch
            {
                return null;
            }
        }
        #endregion
        #region 查詢
        /// <summary>  
        /// 查詢單個物件  
        /// </summary>    
        public static T GetModel<T>(String collectionName, IMongoQuery query)
        {

            MongoCollection<T> collection = mdb.GetCollection<T>(collectionName);
            try
            {
                return collection.FindOneAs<T>(query);
            }
            catch
            {
                return default(T);
            }
        }
        /// <summary>
        /// 查詢物件集合
        /// </summary>
        public static List<T> GetList<T>(String collectionName, IMongoQuery query)
        {
            MongoCollection<T> collection = mdb.GetCollection<T>(collectionName);
            try
            {
                return collection.FindAs<T>(query).ToList();
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 查詢物件集合
        /// </summary>
        public static List<T> GetList<T>(String collectionName, IMongoQuery query, int top)
        {
            MongoCollection<T> collection = mdb.GetCollection<T>(collectionName);
            try
            {
                return collection.FindAs<T>(query).SetLimit(top).ToList();
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 查詢物件集合
        /// </summary>
        public static List<T> GetList<T>(String collectionName, IMongoQuery query, string sort, bool isDesc)
        {
            MongoCollection<T> collection = mdb.GetCollection<T>(collectionName);
            try
            {
                if (isDesc)
                {
                    return collection.FindAs<T>(query).SetSortOrder(SortBy.Descending(sort)).ToList();
                }
                else
                {
                    return collection.FindAs<T>(query).SetSortOrder(SortBy.Ascending(sort)).ToList();
                }
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 查詢物件集合
        /// </summary>
        public static List<T> GetList<T>(String collectionName, IMongoQuery query, string[] sort, bool isDesc)
        {
            MongoCollection<T> collection = mdb.GetCollection<T>(collectionName);
            try
            {
                if (isDesc)
                {
                    return collection.FindAs<T>(query).SetSortOrder(SortBy.Descending(sort)).ToList();
                }
                else
                {
                    return collection.FindAs<T>(query).SetSortOrder(SortBy.Ascending(sort)).ToList();
                }
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 查詢物件集合
        /// </summary>
        public static List<T> GetList<T>(String collectionName, IMongoQuery query, string sort, bool isDesc, int top)
        {
            MongoCollection<T> collection = mdb.GetCollection<T>(collectionName);
            try
            {
                if (isDesc)
                {
                    return collection.FindAs<T>(query).SetSortOrder(SortBy.Descending(sort)).SetLimit(top).ToList();
                }
                else
                {
                    return collection.FindAs<T>(query).SetSortOrder(SortBy.Ascending(sort)).SetLimit(top).ToList();
                }
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 查詢物件集合
        /// </summary>
        public static List<T> GetList<T>(String collectionName, IMongoQuery query, string[] sort, bool isDesc, int top)
        {
            MongoCollection<T> collection = mdb.GetCollection<T>(collectionName);
            try
            {
                if (isDesc)
                {
                    return collection.FindAs<T>(query).SetSortOrder(SortBy.Descending(sort)).SetLimit(top).ToList();
                }
                else
                {
                    return collection.FindAs<T>(query).SetSortOrder(SortBy.Ascending(sort)).SetLimit(top).ToList();
                }
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 分頁查詢
        /// </summary>       
        public static List<T> GetPageList<T>(String collectionName, IMongoQuery query, string sort, bool isDesc, int index, int pageSize, out long rows)
        {
            MongoCollection<T> collection = mdb.GetCollection<T>(collectionName);
            try
            {
                rows = collection.FindAs<T>(query).Count();
                if (isDesc)
                {
                    return collection.FindAs<T>(query).SetSortOrder(SortBy.Descending(sort)).SetSkip(index).SetLimit(pageSize).ToList();
                }
                else
                {
                    return collection.FindAs<T>(query).SetSortOrder(SortBy.Ascending(sort)).SetSkip(index).SetLimit(pageSize).ToList();
                }
            }
            catch
            {
                rows = 0;
                return null;
            }
        }
        /// <summary>
        /// 分頁查詢
        /// </summary>       
        public static List<T> GetPageList<T>(String collectionName, IMongoQuery query, string[] sort, bool isDesc, int index, int pageSize, out long rows)
        {
            MongoCollection<T> collection = mdb.GetCollection<T>(collectionName);
            try
            {
                rows = collection.FindAs<T>(query).Count();
                if (isDesc)
                {
                    return collection.FindAs<T>(query).SetSortOrder(SortBy.Descending(sort)).SetSkip(index).SetLimit(pageSize).ToList();
                }
                else
                {
                    return collection.FindAs<T>(query).SetSortOrder(SortBy.Ascending(sort)).SetSkip(index).SetLimit(pageSize).ToList();
                }
            }
            catch
            {
                rows = 0;
                return null;
            }
        }
        #endregion
        #region 修改
        /// <summary>  
        /// 修改  
        /// </summary>    
        public static WriteConcernResult Update(String collectionName, IMongoQuery query, QueryDocument update)
        {
            MongoCollection<BsonDocument> collection = mdb.GetCollection<BsonDocument>(collectionName);
            try
            {
                var new_doc = new UpdateDocument() { { "$set", update } };
                //UpdateFlags設定為Multi時,可批量修改
                var result = collection.Update(query, new_doc, UpdateFlags.Multi);
                return result;
            }
            catch
            {
                return null;
            }
        }
        #endregion
        #region 移除
        /// <summary>  
        /// 移除匹配的集合
        /// </summary>  
        public static Boolean Remove(String collectionName, IMongoQuery query)
        {

            MongoCollection<BsonDocument> collection = mdb.GetCollection<BsonDocument>(collectionName);
            try
            {
                collection.Remove(query);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>  
        /// 移除所有集合  
        /// </summary>  
        public static Boolean RemoveAll(String collectionName)
        {

            MongoCollection<BsonDocument> collection = mdb.GetCollection<BsonDocument>(collectionName);
            try
            {
                collection.RemoveAll();
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion
        #region 其它
        /// <summary>
        /// 是否存在
        /// </summary>      
        public static bool IsExist(string collectionName)
        {
            MongoCollection<BsonDocument> collection = mdb.GetCollection<BsonDocument>(collectionName);
            try
            {
                return collection.Exists();
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 總數
        /// </summary>      
        public static long Count(string collectionName)
        {
            MongoCollection<BsonDocument> collection = mdb.GetCollection<BsonDocument>(collectionName);
            try
            {
                return collection.Count();
            }
            catch
            {
                return 0;
            }
        }
        /// <summary>
        /// 總數
        /// </summary>    
        public static long Count(string collectionName, IMongoQuery query)
        {
            MongoCollection<BsonDocument> collection = mdb.GetCollection<BsonDocument>(collectionName);
            try
            {
                return collection.Count(query);
            }
            catch
            {
                return 0;
            }
        }
        #endregion
    }

monogodb中where條件操作符號

            Query.And(Query.EQ("name", "a"), Query.EQ("title", "t"));//同時滿足多個條件
            Query.EQ("name", "a");//等於
            Query.Exists("type", true);//判斷鍵值是否存在
            Query.GT("value", 2);//大於>
            Query.GTE("value", 3);//大於等於>=
            Query.In("name", "a", "b");//包括指定的所有值,可以指定不同型別的條件和值
            Query.LT("value", 9);//小於<
            Query.LTE("value", 8);//小於等於<=
            Query.Mod("value", 3, 1);//將查詢值除以第一個給定值,若餘數等於第二個給定值則返回該結果
            Query.NE("name", "c");//不等於
            Query.Nor(Array);//不包括陣列中的值
            Query.Not("name");//元素條件語句
            Query.NotIn("name", "a", 2);//返回與陣列中所有條件都不匹配的文件
            Query.Or(Query.EQ("name", "a"), Query.EQ("title", "t"));//滿足其中一個條件
            Query.Size("name", 2);//給定鍵的長度
            Query.Type("_id", BsonType.ObjectId );//給定鍵的型別
            Query.Where(BsonJavaScript);//執行JavaScript
            Query.Matches("Title",str);//模糊查詢 相當於sql中like  -- str可包含正規表示式

小結

此文程式碼主要是作為倉儲的基方法進行的封裝,當然如果專案結構簡單也可以直接使用操作,如果你有什麼疑問,或者想一起交流學習,歡迎加入左上角的群。同事也歡迎點選觀看, 我的mongodb系列 

 

相關文章