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 页之间跳转时,存 ...
随机推荐
- react 写的省市三级联动
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>Ba ...
- PHP获取页面执行时间的方法
一些循环代码,有时候要知道页面执行的时间,可以添加以下几行代码到页面头部和尾部: 头部: <?php $stime=microtime(true); 尾部: $etime=microtime(t ...
- WNDR3700V4恢复原厂固件(使用TFTP刷网件原厂固件)
WNDR3700v4原厂固件下载地址: http://support.netgear.cn/doucument/More.asp?id=2203 操作方法: 1.将设备断电: 2.按住设备背面的Res ...
- Ceph剖析:数据分布之CRUSH算法与一致性Hash
作者:吴香伟 发表于 2014/09/05 版权声明:可以任意转载,转载时务必以超链接形式标明文章原始出处和作者信息以及版权声明 数据分布是分布式存储系统的一个重要部分,数据分布算法至少要考虑以下三个 ...
- 如何将C++代码逆向生成类图 (VS2013)
1. 将代码添加到VS2013工程中: 2. 切换到"类视图": 3. 选中项目 右键"视图"->"查看类图". 如果项目文件太多的话 ...
- 一个login
login 1.获取提交表单,保存到变量中.2.判断用户密码是否正确,利用Model类.3.验证用户是否激活.3.判断用户是否记住登录状态,是的话,将其用cookie和session分别保存.没有的话 ...
- cassandra安装
从官网下载下来的包解压后有100多M,里面包含了已经编译好的全部程序. 按照方法,进入目录后运行 bin/cassandra -f 运行不成功. 然后根据"https://wiki.apac ...
- [django]在virtualenv下安装的第三方库的使用方法
在virtualenv下安装的第三方库,例如south, requests等,如果想在django中使用,需要先将库添加到settings.py的INSTALLED_APPS中, 以south, re ...
- Android LayoutInflater原理分析,带你一步步深入了解View(一)
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/12921889 有不少朋友跟我反应,都希望我可以写一篇关于View的文章,讲一讲Vi ...
- Jquery打造的类似新浪微博@提醒功能
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...