monodb C#接口封装
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 &. 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#接口封装的更多相关文章
- Java微信公众平台接口封装源码分享
前言: 这篇博客是在三月初动手项目的时候准备写的,但是为了完成项目只好拖延时间写这篇博客,顺便也可以在项目中应用我自己总结的的一些经验.今天看来,这些方法的应用还是可以的,至少实现了我之前的 ...
- C++ Redis mset 二进制数据接口封装方案
C++ Redis mset 二进制数据接口封装方案 需求 C++中使用hiredis客户端接口访问redis: 需要使用mset一次设置多个二进制数据 以下给出三种封装实现方案: 简单拼接方案 在r ...
- hiredis异步接口封装并导出到Lua
hiredis异步接口封装并导出到Lua(金庆的专栏 2017.1)hiredis 不支持 Windows, Windows 下使用 wasppdotorg / hiredis-for-windows ...
- 基于Verilog的带FIFO输出缓冲的串口接收接口封装
一.模块框图及基本思路 rx_module:串口接收的核心模块,详细介绍请见“基于Verilog的串口接收实验” rx2fifo_module:rx_module与rx_fifo之间的控制模块,其功能 ...
- vue2.0 + vux (五)api接口封装 及 首页 轮播图制作
1.安装 jquery 和 whatwg-fetch (优雅的异步请求API) npm install jquery --save npm install whatwg-fetch --save 2. ...
- 基于Zabbix API文档二次开发与java接口封装
(继续贴一篇之前工作期间写的经验案例) 一. 案例背景 我负责开发过一个平台的监控报警模块,基于zabbix实现,需要对zabbix进行二次开发. Zabbix官方提供了Rest ...
- 微信小程序“一劳永逸”的接口封装
前言 最近都在研究小程序了,我可以的! 需求 之前都是用vue来开发项目的,接口模块我特意封装了一下.感觉也可以记录一下 小程序的接口虽说简单,但是重复调用那么多,显得不专业(一本正经的胡说八道) 还 ...
- Plx9030通讯卡驱动开发与接口封装
在学校的时候,曾经采用DDK+Driverstudio+VC6.0环境做过9054视频采集卡的驱动开发,回想起调试过程,记得最清楚的就是过无数次的计算机蓝屏重启....今天第一天来到新公司,老大就说你 ...
- java:Session(概述,三层架构实例(实现接口封装JDBC),Session实现简单购物车实例)
1.Session概述: Session:在计算机中,尤其是在网络应用中,称为“会话控制”.Session 对象存储特定用户会话所需的属性及配置信息.这样,当用户在应用程序的 Web 页之间跳转时,存 ...
随机推荐
- 用Python实现一个爬取XX大学电费通知的小脚本
内容简要 1分析网站 2简单爬取 3进阶自定义爬取 4保存进数据库 学校基础设施太差,宿舍电量过低提醒虽然贴在楼下,但是作为低头一族,经常忘记看提醒导致宿舍酣战时突然黑屏,为了避免这种尴尬的场景以及强 ...
- bootstrap-datepicker使用
$('.date').datepicker({ language: 'zh-CN', --指定格式 format: 'yyyy-mm', --格式要求 autoclose: true, --选择后是否 ...
- MongoDB的真正性能-实战百万用户一-一亿的道具
使用情景 开始之前,我们先设定这样一个情景: 1.一百万注册用户的页游或者手游,这是不温不火的一个状态,刚好是数据量不上不下的一个情况.也刚好是传统MySql数据库性能开始吃紧的时候. 2.数据库就用 ...
- RHEL7关于时间的学习笔记
当你发现时间是贼了,它早已偷光你的选择. 一,GMT.UTC.CST GMT:(Greenwich Mean Time)格林威治时间 ,太阳通过格林威治那一刻来作为计时标准. UTC:(Coordin ...
- CentOS系统下安装配置ftp服务
安装配置步骤: rpm -ivh /opt/bak/vsftpd-2.2.2-11.el6.x86_64.rpm --本地安装vsftpd ll /etc/vsftpd/ --查看vsftpd的配置 ...
- [转载]centos安装svn服务器
一.安装Subversion #yum install subversion 1.查看安装时的文件产生情况,使用 rpm -ql subversion 2.卸载subversion:#yum re ...
- jQuery常用的插件及功能汇总-持续
1.图片轮播 jquery.soChange.js 2.滚动展示 MSClass.js 3.md5加密 md5.js 4.cookie操作 cookie.js 5.
- Highchart使用json格式数据lineDemo
<html> <head> <title>Highcharts Example</title> <script type="text/j ...
- JS-Number
Number 是对原始数据的封装 语法: var myNum=new Number(value);//返回一个新创建的 Number 对象 var myNum=Number(value);//把自己的 ...
- 伟大的GCD和NSOperationQueue
一. GCD GCD中最重要的两个东西 任务 和 队列 任务就是一段代码(用来缓存,下载,计算等操作) 队列从大的方面分为两个队列:主队列(串行队列)和 自己创建的队列(串行,和并行) 主队列中: 在 ...