mongodb的C#封装,驱动是samus/mongodb-csharp

1.连接类

using MongoDB;
using MongoDB.Linq;
namespace DBModel
{
    public class ConnString
    {
        public static string m_connStr = System.Configuration.ConfigurationManager.AppSettings["mongodb_ip"];// "Server=127.0.0.1";
        public static string m_dbName = System.Configuration.ConfigurationManager.AppSettings["mongodb_db"];//"DYZS_DB";
    }
    //对某个表的操作
    public class MongoDatabase : IDisposable
    {
        private Mongo m_mongo;
        private IMongoDatabase m_db;
        private IMongoCollection<Document> m_Collection;
        public string m_msg = string.Empty;
        public bool bOpen = false;
        public MongoDatabase()
        {
            if (string.IsNullOrEmpty(ConnString.m_connStr))
                throw new ArgumentNullException("connectionString");

            m_mongo = new Mongo(ConnString.m_connStr);
            // 立即连接 MongoDB
            m_mongo.Connect();
            bOpen = true;
            if (string.IsNullOrEmpty(ConnString.m_dbName) == false)
                m_db = m_mongo.GetDatabase(ConnString.m_dbName);
        }
        public MongoDatabase(string tableName)
        {
            if (string.IsNullOrEmpty(ConnString.m_connStr))
                throw new ArgumentNullException("connectionString");

            m_mongo = new Mongo(ConnString.m_connStr);
            // 立即连接 MongoDB
            m_mongo.Connect();
            bOpen = true;
            if (string.IsNullOrEmpty(ConnString.m_dbName) == false)
                m_db = m_mongo.GetDatabase(ConnString.m_dbName);
            m_Collection = m_db.GetCollection<Document>(tableName) as MongoCollection<Document>;
        }
        public void Dispose()
        {
            if (m_mongo != null)
            {
                if (bOpen)
                {
                    m_mongo.Disconnect();
                    bOpen = false;
                }
                m_mongo.Dispose();
                m_mongo = null;
            }
        }
        public void SetCollection(string tableName)
        {
            m_Collection = m_db.GetCollection<Document>(tableName) as MongoCollection<Document>;
        }
        // 获取当前连接数据库的指定集合【根据指定名称】
        public IMongoCollection GetCollection(string name)
        {
            return this.m_db.GetCollection(name);
        }
        // 获取当前连接数据库的指定集合【依据类型】
        public IMongoCollection<T> GetCollection<T>() where T : class
        {
            return this.m_db.GetCollection<T>();
        }
        public Document Find(object value, string key = "_id")
        {
          return  m_Collection.FindOne(new Document{{ key, value}});
        }
        public Document Find(Document query)
        {
            return m_Collection.FindOne(query);
        }
        public long Count(Document query)
        {
            return m_Collection.Count(query);
        }
        public void Delete(string value, string key = "_id")
        {
            m_Collection.Remove(new Document{{ key, value}});
        }
        public void Delete(Document query)
        {
            m_Collection.Remove(query);
        }
        //db.ids .findAndModify({update:{$inc:{'id':1}}, query:{"name":"user"}, new:true});
       //modify a document (at most one) and return it
        //有点慢
        public Document FindAndModify(Document query, Document set)
        {
            return m_Collection.FindAndModify(set, query, true);
        }
        public int Save(Document query, Document doc)
        {
            try
            {
                string _id = UtilData.toString(doc["_id"]);
                if (_id == string.Empty)//如果没有_id
                {
                    _id = MongoDB.Oid.NewOid().ToString();
                }

                if (m_Collection.FindOne(query) == null)
                {
                    doc["_id"] = _id;
                    m_Collection.Insert(doc);
                }
                else
                {
                    doc["_id"] = _id;
                    m_Collection.Save(doc);
                }
            }
            catch
            {
                ;
            }
            ;
        }
    //1.update方法如果是要更新文档中的一个或几个属性的时候,必须要用形如{$set:{age:33}}的形式,否则被覆盖。
    //2.update方法默认是只更新找到的第一个文档,如果需要所有的文档都更新,则需要在option部分再加上{multi:true},
    //如果想要在查找不到这条记录的时候新增一条,则要在option部分加上{upsert:true}。 

        public int Update(Document query, Document set)
        {
            try
            {
                m_Collection.Update(set, query);
            }
            catch
            {
                ;
            }
            ;
        }
        public int UpdateAll(Document query, Document set)
        {
            try
            {
                m_Collection.Update(set, query,UpdateFlags.MultiUpdate);
            }
            catch
            {
                ;
            }
            ;
        }
        //新建
        public string Insert(Document doc, string key = "_id")
        {
            string id = UtilData.toString(doc[key]);
            if (id == string.Empty)
            {
                id = MongoDB.Oid.NewOid().ToString();
                doc[key] = id;
            }

            m_Collection.Save(doc);
            return id;
        }
    }
}

2.表操作基类

public class MongoBasicOper
    {
        public string m_TableName = string.Empty;
        public string m_Msg = string.Empty;
        public MongoBasicOper()
        {
        }
        public MongoBasicOper(string table)
        {
            m_TableName = table;
        }
        public void SetTable(string table)
        {
            m_TableName = table;
        }
        public Document GetRow(object value, string key = "_id")
        {
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                return mongo.Find(value, key);
            }
        }
        public Document GetRow(Document query)
        {
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                return mongo.Find(query);
            }
        }

        public long Count(Document query)
        {
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                return mongo.Count(query);
            }
        }
        public string Insert(Document doc)
        {
            if (UtilData.toString(doc["_id"]) == string.Empty)
            {
                string id = MongoDB.Oid.NewOid().ToString();
                doc["_id"] = id;
            }
            MongoDatabase mongo = null;
            try
            {
                mongo = new MongoDatabase(m_TableName);
                mongo.Insert(doc);
            }
            catch(Exception e)
            {
                m_Msg = e.Message;
                return null;
            }
            finally
            {
                mongo.Dispose();
            }
            return UtilData.toString(doc["_id"]);
        }

        //不需要加update,需要加$set
        public Document FindAndModify(Document query, Document set)
        {
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                return mongo.FindAndModify(query, set);
            }
        }

        //有则替换,无则插入
        public int Save (string _id, Document doc)
        {
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                return mongo.Save(new Document("_id",_id),doc);
            }
        }
        //有则替换,无则插入
        public int Save(Document query, Document doc)
        {
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                return mongo.Save(query,doc);
            }
        }

        //替换
        public int Replace(string _id, Document doc)
        {
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                return mongo.Update(new Document() { { "_id", _id } }, doc);
            }
        }
        //部分更新,单行
        public int Set(string _id, Document doc)
        {
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                Document set = new Document();
                set.Add("$set", doc);
                return mongo.Update(new Document(){ {"_id",_id} }, set);
            }
        }

        //部分更新,多行
        public int Set(Document query, Document doc)
        {
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                Document set = new Document();
                set.Add("$set", doc);
                return mongo.UpdateAll(query, set);
            }
        }

        //创建
        public string Insert(Document doc, string key = "_id")
        {
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                return mongo.Insert(doc, key);
            }
        }
        //keyVal是查找值
        , string key = "_id")
        {
            Document query = new Document(key, keyVal);

            Document doc = new Document(colName, addVal);
            Document docInc = new Document("$inc", doc);
            var row = FindAndModify(query, docInc);
            if (row == null)
            {

                query.Add(colName, addVal);
                Insert(query);
                row = GetRow(keyVal, key);
            }
            ;
            UtilData.toInt(row[colName], ref val);
            return val;
        }        

        public void Delete(string val)
        {
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                mongo.Delete(val);
            }
        }
        public void Delete(Document query)
        {
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                mongo.Delete(query);
            }
        }
        //page从1开始
        public List<Document> GetList(List<string> lstColName, Document query, JqGridParam jqParam, ref int count)
        {
            Document sort = new Document();
            jqParam.sidx = UtilData.toString(jqParam.sidx);
            jqParam.sord = UtilData.toString(jqParam.sord);
            if (jqParam.sidx == string.Empty)
            {
                jqParam.sidx = "Time";
            }
            var arrIndex = jqParam.sidx.Split(',');
            int[] arrSort = new int[arrIndex.Length];
            ; i < arrSort.Length; i++)
            {
                sort.Add(arrIndex[i], -);
            }

            if (!string.IsNullOrEmpty(jqParam.sord))
            {
                var arr2 = jqParam.sord.Split(',');
                ; i < arr2.Length; i++)
                {
                    if (i >= arrSort.Length) break;

                    ")
                    {
                        sort[arrIndex[i]] = ;
                    }
                }
            }
            return GetList(lstColName,query,sort,jqParam, ref  count);
        }
        public List<Document> GetList(List<string> lstColName, Document query, Document sort, JqGridParam jqParam, ref int count)
        {
            List<Document> lstRes = new List<Document>();
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {
                IMongoCollection collection = mongo.GetCollection(m_TableName);//打开db数据库中的table表
                count = (int)collection.Count(query);

                )
                {
                    jqParam.page = ;
                }
                 && count <= (jqParam.page - ) * jqParam.rows)
                {
                    jqParam.page = ( ?  : );
                }

                )
                {
                    )
                    {
                        jqParam.page = ;
                    }
                    )
                    {
                        jqParam.page = (int)Math.Ceiling((float)count / (float)jqParam.rows);
                    }
                    ) * jqParam.rows).Limit(jqParam.rows);
                    string colName = string.Empty;
                    foreach (Document docx in cursor2.Documents)
                    {
                        Document doc = new Document();
                        ; i < lstColName.Count; i++)
                        {
                            colName = lstColName[i];
                            doc[colName] = docx[colName];
                        }
                        lstRes.Add(doc);
                    }

                }
            }
            return lstRes;
        }
        public List<Document> GetTopRow(List<string> lstColName, Document query, Document sort, int top)
        {
            List<Document> lstRes = new List<Document>();
            using (MongoDatabase mongo = new MongoDatabase(m_TableName))
            {

                IMongoCollection collection = mongo.GetCollection(m_TableName);//打开db数据库中的table表
                ICursor cursor;
                )
                {
                    cursor = collection.Find(query).Sort(sort).Limit(top);
                }
                else
                {
                    if (sort == null)
                    {
                        cursor = collection.Find(query);
                    }
                    else
                    {
                        cursor = collection.Find(query).Sort(sort);
                    }
                }

                string colName = string.Empty;
                foreach (Document docx in cursor.Documents)
                {
                    Document doc = new Document();
                    ; i < lstColName.Count; i++)
                    {
                        colName = lstColName[i];
                        doc[colName] = docx[colName];
                    }
                    lstRes.Add(doc);
                }
            }
            return lstRes;
        }

        //方便前台处理,全部转换为string类型
        public List<Document> GetListEx(List<string> lstColName, Document query, JqGridParam jqParam, ref int count)
        {
            var lstRes = GetList(lstColName, query, jqParam, ref count);

            string colName = string.Empty;
            foreach (Document doc in lstRes)
            {
                ; i < lstColName.Count; i++)
                {
                    colName = lstColName[i];
                    doc[colName] = UtilData.toView(doc[colName]);
                }
            }
            return lstRes;
        }
        //public ICursor GetList(int rows, int page, ref int count)
        //{
        //    using (MonDB mongo = new MonDB(m_TableName))
        //    {
        //        var collection = mongo.GetCollection<Customer>();
        //        var query2 = from c in collection.Linq()
        //                     where c._id == "1"
        //                     select c;
        //        count = query2.Count();
        //        return query2.Skip(rows * page - 1).Take(rows).ToList();
        //IMongoCollection col = db.GetCollection("table");//打开db数据库中的table表
        //ICursor cur = col.Find(query).Skip(10).Limit(100);//从第10条记录开始查询每页显示100条
        //foreach (Document docx in cur.Documents)
        //{
        //Response.Write(docx["id"]+"</br>");
        //}
        //    }
        //}
    }

3.查询封装类

public class DocOP : Document
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DocOP"/> class.
        /// </summary>
        /// <remarks>Only allow instantiation through static methods.</remarks>
        private DocOP()
        { }

        /// <summary>
        /// Matches an object which is greater than the specified value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static DocOP GreaterThan<T>(T value)
        {
            return (DocOP)new DocOP().Add("$gt", value);
        }

        /// <summary>
        /// Matches an object which is greater than or equal to the specified value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static DocOP GreaterThanOrEqual<T>(T value)
        {
            return (DocOP)new DocOP().Add("$gte", value);
        }

        /// <summary>
        /// Matches an object which is less than the specified value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static DocOP LessThan<T>(T value)
        {
            return (DocOP)new DocOP().Add("$lt", value);
        }

        /// <summary>
        /// Matches an object which is less than or equal to the specified value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static DocOP LessThanOrEqual<T>(T value)
        {
            return (DocOP)new DocOP().Add("$lte", value);
        }

        /// <summary>
        /// Matches an object which does not equal the specified value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static DocOP NotEqual<T>(T value)
        {
            return (DocOP)new DocOP().Add("$ne", value);
        }

        /// <summary>
        /// Matches an array which has one of the specified values.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="values">The values.</param>
        /// <returns></returns>
        public static DocOP In<T>(params T[] values)
        {
            return (DocOP)new DocOP().Add("$in", values);
        }

        /// <summary>
        /// Matches an array which does not have any of the specified values.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="values">The values.</param>
        /// <returns></returns>
        public static DocOP NotIn<T>(params T[] values)
        {
            return (DocOP)new DocOP().Add("$nin", values);
        }

        /// <summary>
        /// Matches an array which has all of the specified values.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="values">The values.</param>
        /// <returns></returns>
        public static DocOP All<T>(params T[] values)
        {
            return (DocOP)new DocOP().Add("$all", values);
        }

        /// <summary>
        /// Modulus operator.
        /// </summary>
        /// <param name="denominator">The denominator.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public static DocOP Mod(int denominator, int result)
        {
            return (DocOP)new DocOP().Add("$mod", new[] { denominator, result });
        }

        /// <summary>
        /// Matches any array with the specified number of elements
        /// </summary>
        /// <param name="size">The size.</param>
        /// <returns></returns>
        public static DocOP Size(int size)
        {
            return (DocOP)new DocOP().Add("$size", size);
        }

        /// <summary>
        /// Check for existence of a field.
        /// </summary>
        /// <returns></returns>
        public static DocOP Exists()
        {
            return (DocOP)new DocOP().Add("$exists", true);
        }

        /// <summary>
        /// Check for lack of existence of a field.
        /// </summary>
        /// <returns></returns>
        public static DocOP NotExists()
        {
            return (DocOP)new DocOP().Add("$exists", false);
        }

        /// <summary>
        /// Matches values based on their bson type.
        /// </summary>
        /// <param name="bsonType">Type of the bson.</param>
        /// <returns></returns>
        public static DocOP Type(BsonType bsonType)
        {
            return (DocOP)new DocOP().Add("$type", (int)bsonType);
        }

        /// <summary>
        /// Sends the Javascript expressiosn to the server.
        /// </summary>
        /// <param name="javascript">The javascript.</param>
        /// <returns></returns>
        public static DocOP Where(string javascript)
        {
            if(javascript == null)
                throw new ArgumentNullException("javascript");

            return (DocOP)new DocOP().Add("$where", new Code(javascript));
        }

        /// <summary>
        /// Implements the operator &amp;.  This is used for conjunctions.
        /// </summary>
        /// <param name="op1">The op1.</param>
        /// <param name="op2">The op2.</param>
        /// <returns>The result of the operator.</returns>
        public static DocOP operator &(DocOP op1, DocOP op2)
        {
            return (DocOP)new DocOP().Merge(op1).Merge(op2);
        }
        /// <summary>
        /// Implements the operator !. This is used for the meta operator $not.
        /// </summary>
        /// <param name="DocOP">The DocOP.</param>
        /// <returns>The result of the operator.</returns>
        public static DocOP operator !(DocOP DocOP)
        {
            return (DocOP)new DocOP().Add("$not", DocOP);
        }

        public static DocOP or(Document op1, Document op2)
        {
            var query = new DocOP
            {
                {"$or", new Document[] { op1,op2} }
            };
            return query;
        }
        public static DocOP and(Document op1, Document op2)
        {
            var query = new DocOP
            {
                {"$and", new Document[] { op1,op2} }
            };
            return query;
        }
        //var query = new Document
        //{
        //    {"$or", new Document[] { new Document("Age", 21), new Document("Age", 35) } }
        //};
    }

4.表继承类

public class LogOper : MongoBasicOper
    {
        public LogOper()
        {
            m_TableName = "T_LOG";
        }
        public string Add(string Catalog, string Title,string By)
        {
            MongoDB.Document doc = new MongoDB.Document();
            doc[DColName.Catalog] = Catalog;
            doc[DColName.Title] = Title;
            doc[DColName.By] = By;
            doc[DColName.Time] = DateTime.Now;
            return Insert(doc);
        }
    }

public class LOG
{
private static LogOper log = new LogOper();
public static void Add(string Catalog, string Title,string By)
{
log.Add(Catalog, Title,By);
}
}

 

5.使用

LOG.Add(LogEnum.系统管理.ToString(), err, string.Empty);

monodb C#接口封装的更多相关文章

  1. Java微信公众平台接口封装源码分享

    前言:      这篇博客是在三月初动手项目的时候准备写的,但是为了完成项目只好拖延时间写这篇博客,顺便也可以在项目中应用我自己总结的的一些经验.今天看来,这些方法的应用还是可以的,至少实现了我之前的 ...

  2. C++ Redis mset 二进制数据接口封装方案

    C++ Redis mset 二进制数据接口封装方案 需求 C++中使用hiredis客户端接口访问redis: 需要使用mset一次设置多个二进制数据 以下给出三种封装实现方案: 简单拼接方案 在r ...

  3. hiredis异步接口封装并导出到Lua

    hiredis异步接口封装并导出到Lua(金庆的专栏 2017.1)hiredis 不支持 Windows, Windows 下使用 wasppdotorg / hiredis-for-windows ...

  4. 基于Verilog的带FIFO输出缓冲的串口接收接口封装

    一.模块框图及基本思路 rx_module:串口接收的核心模块,详细介绍请见“基于Verilog的串口接收实验” rx2fifo_module:rx_module与rx_fifo之间的控制模块,其功能 ...

  5. vue2.0 + vux (五)api接口封装 及 首页 轮播图制作

    1.安装 jquery 和 whatwg-fetch (优雅的异步请求API) npm install jquery --save npm install whatwg-fetch --save 2. ...

  6. 基于Zabbix API文档二次开发与java接口封装

    (继续贴一篇之前工作期间写的经验案例) 一.           案例背景 我负责开发过一个平台的监控报警模块,基于zabbix实现,需要对zabbix进行二次开发. Zabbix官方提供了Rest ...

  7. 微信小程序“一劳永逸”的接口封装

    前言 最近都在研究小程序了,我可以的! 需求 之前都是用vue来开发项目的,接口模块我特意封装了一下.感觉也可以记录一下 小程序的接口虽说简单,但是重复调用那么多,显得不专业(一本正经的胡说八道) 还 ...

  8. Plx9030通讯卡驱动开发与接口封装

    在学校的时候,曾经采用DDK+Driverstudio+VC6.0环境做过9054视频采集卡的驱动开发,回想起调试过程,记得最清楚的就是过无数次的计算机蓝屏重启....今天第一天来到新公司,老大就说你 ...

  9. java:Session(概述,三层架构实例(实现接口封装JDBC),Session实现简单购物车实例)

    1.Session概述: Session:在计算机中,尤其是在网络应用中,称为“会话控制”.Session 对象存储特定用户会话所需的属性及配置信息.这样,当用户在应用程序的 Web 页之间跳转时,存 ...

随机推荐

  1. SVN 集中式版本控制软件

    简介: 目前流行的版本控制软件中,SVN ( 集中式版本控制 ) 算是使用范围更广.且使用时间更早的一款了,现在 git ( 分布式版本控制 ) 更火爆一点. 一.安装svn [root@localh ...

  2. LSD-SLAM深入学习(1)-基本介绍与ros下的安装

    前言 借鉴来自RGB-D数据处理的两种方法-基于特征与基于整体的,同样可以考虑整个图片的匹配,而不是只考虑特征点的…… 一般这种稠密的方法需要很大的计算量,DTAM: Dense tracking a ...

  3. python迭代器和生成器

    迭代器 #可以被netxt()函数调用不断返回一个值的对象成为迭代器:Iterator #迭代器是访问集合元素的一种方式,从集合第一个元素开始(用next()方法)访问就不能回退,便于循环遍历一些较大 ...

  4. 关于meta标签

    一.Meta标签中的format-detection属性及含义 意为:格式检测 或许你会有这样的经历:当你在制作手机端的页面中,点击了没有加任何链接的格式的数字时,这时手机会进行自动拔号提示操作! 禁 ...

  5. Jquery基础知识

    //使用$操作得到的对象,都是Jquery对象 如何把Jquery对象转换成dom对象?$abc 方法1:var div = $div.get(0) 方法2:var div = $div[0] 如何把 ...

  6. python json模块

    import json dic = {"name":"liao","age":18} data = json.dumps(dic) #转化为 ...

  7. 微信公众账号开发之N个坑(一)

    我这人干活没有前奏,喜欢直接开始.完了,宝宝已经被你们带污了.. 微信公众账号开发文档,官方版(https://mp.weixin.qq.com/wiki),相信我,我已经无力吐槽写这个文档的人了,我 ...

  8. [12]APUE:高级 I/O

    一.分散聚离(向量) I/O [a] readv / writev #include <sys/uio.h> ssize_t readv(int fd, const struct iove ...

  9. EF支持mysq相关配置数码

    最近,项目考虑到安装部署方面:希望可以使用MySQL数据库,毕竟比较小巧.方便. 后来,自己通过测试发现EF可以支持mysql数据库,而且也可以通过codefirst模式进行开发:使用起来,跟sqls ...

  10. easyui datagrid加载json

      服务端: string pseries = context.Request["ajaxSearch"].ToString().Trim(); var jsonMap = new ...