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 页之间跳转时,存 ...
随机推荐
- [问题记录.dotnet]取网卡信息报错"找不到"-WMI - Not found
异常: System.Management.ManagementException: 找不到 在 System.Management.ManagementException.ThrowWith ...
- Linux 流程控制语句 if else、for、while、until
1. 单分支if条件语句 书写方式1: if [ 条件判断式 ]; then 执行程序代码 fi 书写方式2: if [ 条件判断式 ] then 执行程序代码 fi 举例: if [ $rate - ...
- Centos | Linux 下安装启动 mysql 出现 8618 [ERROR] Aborting,查看日志:Plugin 'FEDERATED' is disabled.
1.试试启动时指定配置文件 ./bin/mysqld_safe --defaults-file=mysql.cnf 或 ./bin/mysqld_safe --defaults-file=mysql. ...
- oracle数据库升级记(记一次10.2.0.3版本升级到11.2.0.1版本的过程)
操作系统:windows xp 已有数据库版本:10.2.0.3 升级目标版本:11.2.0.1 步骤大纲: 在源操作系统(安装有10.2.0.3数据库的操作系统)上安装11.2.0.1数据库软件,然 ...
- 下拉框数据的动态选择,类似级联ajax刷新数据
简单的两个下拉列表,第二个中的数据与第一个下拉框相关: --------------------var selected = $(this).children('option:selected').v ...
- sql update多表联合更新
update tabA set PrintTag=c.dp_state from tabA a inner join tabB b on a.Code=b.design inner join tabC ...
- Linux SVN 命令详解(zz)
Linux下常用SVN命令 2012-04-02 11:46:00 标签:服务器 目录 Linux checkout linux系统 1.将文件checkout到本地目录 svn checkout p ...
- R语言读取excel文件的3种方法
R读取excel文件中数据的方法: 电脑有一个excel文件,原始的文件路径是:E:\R workshop\mydata\biom excel数据为5乘2阶矩阵,元素为 ...
- gcc 常用命令行及解释
gcc - GNU project C and C++ compiler gcc [option] file... preprocessing compila ...
- Mysql监控、优化
一.查询语句的生命周期 1.MYSQL服务器监听3306端口 2.验证访问用户 3.创建MySQL线程 4.检查内存(Qcache),当查询命中缓存,MYSQL立刻返回结果,跳过解析.优化.执行阶段. ...