c#操作MangoDB 之MangoDB CSharp Driver驱动详解
序言
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 = ;
//最大闲置时间
config.MaxConnectionIdleTime = TimeSpan.FromSeconds();
//最大存活时间
config.MaxConnectionLifeTime = TimeSpan.FromSeconds();
//链接时间
config.ConnectTimeout = TimeSpan.FromSeconds();
//等待队列大小
config.WaitQueueSize = ;
//socket超时时间
config.SocketTimeout = TimeSpan.FromSeconds();
//队列等待时间
config.WaitQueueTimeout = TimeSpan.FromSeconds();
//操作时间
config.OperationTimeout = TimeSpan.FromSeconds();
}
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 = ;
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 = ;
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 ;
}
}
/// <summary>
/// 总数
/// </summary>
public static long Count(string collectionName, IMongoQuery query)
{
MongoCollection<BsonDocument> collection = mdb.GetCollection<BsonDocument>(collectionName);
try
{
return collection.Count(query);
}
catch
{
return ;
}
}
#endregion
}
monogodb中where条件操作符号
Query.And(Query.EQ("name", "a"), Query.EQ("title", "t"));//同时满足多个条件
Query.EQ("name", "a");//等于
Query.Exists("type", true);//判断键值是否存在
Query.GT("value", );//大于>
Query.GTE("value", );//大于等于>=
Query.In("name", "a", "b");//包括指定的所有值,可以指定不同类型的条件和值
Query.LT("value", );//小于<
Query.LTE("value", );//小于等于<=
Query.Mod("value", , );//将查询值除以第一个给定值,若余数等于第二个给定值则返回该结果
Query.NE("name", "c");//不等于
Query.Nor(Array);//不包括数组中的值
Query.Not("name");//元素条件语句
Query.NotIn("name", "a", );//返回与数组中所有条件都不匹配的文档
Query.Or(Query.EQ("name", "a"), Query.EQ("title", "t"));//满足其中一个条件
Query.Size("name", );//给定键的长度
Query.Type("_id", BsonType.ObjectId );//给定键的类型
Query.Where(BsonJavaScript);//执行JavaScript
Query.Matches("Title",str);//模糊查询 相当于sql中like -- str可包含正则表达式
小结
此文代码主要是作为仓储的基方法进行的封装,当然如果项目结构简单也可以直接使用操作,如果你有什么疑问,或者想一起交流学习,欢迎加入左上角的群。同事也欢迎点击观看, 我的mongodb系列
c#操作MangoDB 之MangoDB CSharp Driver驱动详解的更多相关文章
- linux usb 驱动详解
linux usb 驱动详解 USB 设备驱动代码通过urb和所有的 USB 设备通讯.urb用 struct urb 结构描述(include/linux/usb.h ). urb 以一种异步的方式 ...
- 25.Linux-Nor Flash驱动(详解)
1.nor硬件介绍: 从原理图中我们能看到NOR FLASH有地址线,有数据线,它和我们的SDRAM接口相似,能直接读取数据,但是不能像SDRAM直接写入数据,需要有命令才行 1.1其中我们2440的 ...
- 16.Linux-LCD驱动(详解)
在上一节LCD层次分析中,得出写个LCD驱动入口函数,需要以下4步: 1) 分配一个fb_info结构体: framebuffer_alloc(); 2) 设置fb_info 3) 设置硬件相关的操作 ...
- 16.Linux-LCD驱动(详解)【转】
转自:https://www.cnblogs.com/lifexy/p/7604011.html 在上一节LCD层次分析中,得出写个LCD驱动入口函数,需要以下4步: 1) 分配一个fb_info结构 ...
- 使用VS2010编译MongoDB C++驱动详解
最近为了解决IM消息记录的高速度写入.多文档类型支持的需求,决定使用MongoDB来解决. 考虑到MongoDB对VS版本要求较高,与我现有的VS版本不兼容,在leveldb.ssdb.redis.h ...
- shell编程系列23--shell操作数据库实战之mysql命令参数详解
shell编程系列23--shell操作数据库实战之mysql命令参数详解 mysql命令参数详解 -u 用户名 -p 用户密码 -h 服务器ip地址 -D 连接的数据库 -N 不输出列信息 -B 使 ...
- Linux下usb设备驱动详解
USB驱动分为两块,一块是USB的bus驱动,这个东西,Linux内核已经做好了,我们可以不管,我们只需要了解它的功能.形象的说,USB的bus驱动相当于铺出一条路来,让所有的信息都可以通过这条USB ...
- 基于Linux的tty架构及UART驱动详解
更多嵌入式Linux原创,请关注公众号:一口Linux 一.模块硬件学习 1.1. Uart介绍 通用异步收发传输器(Universal Asynchronous Receiver/Transmitt ...
- 21.Linux-写USB键盘驱动(详解)
本节目的: 根据上节写的USB鼠标驱动,来依葫芦画瓢写出键盘驱动 1.首先我们通过上节的代码中修改,来打印下键盘驱动的数据到底是怎样的 先来回忆下,我们之前写的鼠标驱动的id_table是这样: 所以 ...
随机推荐
- .Net多线程编程—并发集合
并发集合 1 为什么使用并发集合? 原因主要有以下几点: System.Collections和System.Collections.Generic名称空间中所提供的经典列表.集合和数组都不是线程安全 ...
- KMP算法求解
// KMP.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include<iostream> using namespac ...
- transtion:过渡动画
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 17.0px Monaco; color: #4f5d66 } p.p2 { margin: 0.0px 0 ...
- 02.LoT.UI 前后台通用框架分解系列之——灵活的菜单栏
LOT.UI分解系列汇总:http://www.cnblogs.com/dunitian/p/4822808.html#lotui LoT.UI开源地址如下:https://github.com/du ...
- ASP.NET Core中如影随形的”依赖注入”[上]: 从两个不同的ServiceProvider说起
我们一致在说 ASP.NET Core广泛地使用到了依赖注入,通过前面两个系列的介绍,相信读者朋友已经体会到了这一点.由于前面两章已经涵盖了依赖注入在管道构建过程中以及管道在处理请求过程的应用,但是内 ...
- IE8/9 JQuery.Ajax 上传文件无效
IE8/9 JQuery.Ajax 上传文件有两个限制: 使用 JQuery.Ajax 无法上传文件(因为无法使用 FormData,FormData 是 HTML5 的一个特性,IE8/9 不支持) ...
- 深入解析Sqlite的完美替代者,android数据库新王者——Realm
写在前面: 又到一年一度七夕虐狗节,看着大家忍受着各种朋友圈和QQ空间还有现实生活中的轮番轰炸,我实在不忍心再在这里给大家补刀,所以我觉得今天不虐狗,继续给大家分享有用的. 如果你比较关心androi ...
- 餐饮连锁公司IT信息化解决方案一
从餐饮企业的信息化需求来说,没有哪一种解决方案能满足所有餐饮企业的信息化建设需要.不同的餐饮业态有不同的业务流程,不同业态的信息化解决方案是目前餐饮企业信息化建设急需的,这种一站式整 ...
- PHP设计模式(七)适配器模式(Adapter For PHP)
适配器模式:将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作. 如下图(借图): // 设置书的接口 // 书接口 interface BookI ...
- Cocos2d-x不要随便在onEnter里面addChild
使用任何版本的Cocos2d-x(1.x,2.x,3.0),在onEnter中调用addChild,都要小心谨慎,因为它有可能导致两种莫名其妙的BUG,莫名其妙的BUG当然难以定位了!更何况这个BUG ...