c#操作MangoDB 之MangoDB CSharp Driver驱动详解

摘要:
驱动器的具体介绍:https://docs.mongodb.org/ecosystem/drivers/csharp/本文主要为c#操作mongodb的添加、删除、修改和查询以及数据库链接配置提供代码示例,以便于进一步封装和学习。
序言

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系列 

免责声明:文章转载自《c#操作MangoDB 之MangoDB CSharp Driver驱动详解》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Qt QSS QCheckBox和QRadioButton在码云上添加公钥时提示不允许重复添加(实际上当前公钥数为0)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Drools介绍与使用

Drools 是用 Java 语言编写的开放源码规则引擎,使用 Rete 算法对所编写的规则求值。Drools 允许使用声明方式表达业务逻辑。可以使用非 XML 的本地语言编写规则,从而便于学习和理解。并且,还可以将 Java 代码直接嵌入到规则文件中,这令 Drools 的学习更加吸引人。 Drools 还具有其他优点: 非常活跃的社区支持 易用 快...

Java中针对Yaml格式数据操作记录

写在前面 最近由于涉及的功能需要对Nacos配置信息通过代码实现发布,在此过程中,涉及到String字符串转换Map,Map转换为Yaml格式的字符串等方法,由于之前没有接触过此方面内容,所以特在此进行记录,以做备忘! 1、Nacos获取配置 Nacos获取配置信息,返回结果为String格式字符串,这里可以参看Nacos中文文档(地址为:https://...

C#批量附加指定目录下的所有数据库文件到数据库中

应用场合:因为经常更换操作系统,所以D盘存放数据库文件目录的数据库每次都要一个一个的附加到MSSQL中,因此设计程序批量附加省时间也方便自己和大家。 程序不足:没有去研究跟实现NDF日志文件附加和多个日志文件的数据库附加。 程序源码:         /// <summary>         /// 循环查找指定目录下要附加的数据库文件和对...

利用JavaCSV API来读写csv文件

http://blog.csdn.net/loongshawn/article/details/53423121 http://javacsv.sourceforge.net/ 转载请注明来源-作者@loongshawn:http://blog.csdn.net/loongshawn/article/details/53423121 1 背景 CSV文件...

ORACLE 如何查看索引重建进度情况

   在ORACLE数据库中,如果一个比较大的索引在重建过程中耗费时间比较长,那么怎么查看索引重建耗费的时间,以及完成了多少(比例)了呢,我们可以通过V$SESSION_LONGOPS视图来查看索引重建的时间和进度。   官方文档关于V$SESSION_LONGOPS的介绍如下 V$SESSION_LONGOPS This view displays...

干货分享:ASP.NET CORE(C#)与Spring Boot MVC(JAVA)异曲同工的编程方式总结

我(梦在旅途,http://zuowj.cnblogs.com; http://www.zuowenjun.cn)最近发表的一篇文章《.NET CORE与Spring Boot编写控制台程序应有的优雅姿势》看到都上48小时阅读排行榜(当然之前发表的文章也有哦!),说明关注.NET CORE及Spring Boot的人很多,也是目前的主流方向,于是我便决定系...