序言

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驱动详解的更多相关文章

  1. linux usb 驱动详解

    linux usb 驱动详解 USB 设备驱动代码通过urb和所有的 USB 设备通讯.urb用 struct urb 结构描述(include/linux/usb.h ). urb 以一种异步的方式 ...

  2. 25.Linux-Nor Flash驱动(详解)

    1.nor硬件介绍: 从原理图中我们能看到NOR FLASH有地址线,有数据线,它和我们的SDRAM接口相似,能直接读取数据,但是不能像SDRAM直接写入数据,需要有命令才行 1.1其中我们2440的 ...

  3. 16.Linux-LCD驱动(详解)

    在上一节LCD层次分析中,得出写个LCD驱动入口函数,需要以下4步: 1) 分配一个fb_info结构体: framebuffer_alloc(); 2) 设置fb_info 3) 设置硬件相关的操作 ...

  4. 16.Linux-LCD驱动(详解)【转】

    转自:https://www.cnblogs.com/lifexy/p/7604011.html 在上一节LCD层次分析中,得出写个LCD驱动入口函数,需要以下4步: 1) 分配一个fb_info结构 ...

  5. 使用VS2010编译MongoDB C++驱动详解

    最近为了解决IM消息记录的高速度写入.多文档类型支持的需求,决定使用MongoDB来解决. 考虑到MongoDB对VS版本要求较高,与我现有的VS版本不兼容,在leveldb.ssdb.redis.h ...

  6. shell编程系列23--shell操作数据库实战之mysql命令参数详解

    shell编程系列23--shell操作数据库实战之mysql命令参数详解 mysql命令参数详解 -u 用户名 -p 用户密码 -h 服务器ip地址 -D 连接的数据库 -N 不输出列信息 -B 使 ...

  7. Linux下usb设备驱动详解

    USB驱动分为两块,一块是USB的bus驱动,这个东西,Linux内核已经做好了,我们可以不管,我们只需要了解它的功能.形象的说,USB的bus驱动相当于铺出一条路来,让所有的信息都可以通过这条USB ...

  8. 基于Linux的tty架构及UART驱动详解

    更多嵌入式Linux原创,请关注公众号:一口Linux 一.模块硬件学习 1.1. Uart介绍 通用异步收发传输器(Universal Asynchronous Receiver/Transmitt ...

  9. 21.Linux-写USB键盘驱动(详解)

    本节目的: 根据上节写的USB鼠标驱动,来依葫芦画瓢写出键盘驱动 1.首先我们通过上节的代码中修改,来打印下键盘驱动的数据到底是怎样的 先来回忆下,我们之前写的鼠标驱动的id_table是这样: 所以 ...

随机推荐

  1. Elasticsearch 5.0 中term 查询和match 查询的认识

    Elasticsearch 5.0 关于term query和match query的认识 一.基本情况 前言:term query和match query牵扯的东西比较多,例如分词器.mapping ...

  2. Oracle 的基本操作符

    != 不等于 select empno,ename,job from scott.emp where job!='manager' ^= 不等于 select empno,ename,job from ...

  3. JavaScript 字符串实用常操纪要

    JavaScript 字符串用于存储和处理文本.因此在编写 JS 代码之时她总如影随形,在你处理用户的输入数据的时候,在读取或设置 DOM 对象的属性时,在操作 Cookie 时,在转换各种不同 Da ...

  4. excel 日期/数字格式不生效需要但双击才会生效的解决办法

    原因: Excel2007设置过单元格格式后,并不能立即生效必须挨个双击单元格,才能生效.数据行很多.效率太低. 原因:主要是一些从网上拷贝过来的日期或数字excel默认为文本格式或特殊-中文数字格式 ...

  5. WebApi接口 - 响应输出xml和json

    格式化数据这东西,主要看需要的运用场景,今天和大家分享的是webapi格式化数据,这里面的例子主要是输出json和xml的格式数据,测试用例很接近实际常用情况:希望大家喜欢,也希望各位多多扫码支持和点 ...

  6. Golang 编写的图片压缩程序,质量、尺寸压缩,批量、单张压缩

    目录: 前序 效果图 简介 全部代码 前序: 接触 golang 不久,一直是边学边做,边总结,深深感到这门语言的魅力,等下要跟大家分享是最近项目 服务端 用到的图片压缩程序,我单独分离了出来,做成了 ...

  7. 【夯实Nginx基础】Nginx工作原理和优化、漏洞

    本文地址 原文地址 本文提纲: 1.  Nginx的模块与工作原理    2.  Nginx的进程模型    3 . NginxFastCGI运行原理        3.1 什么是 FastCGI   ...

  8. 【从零开始学BPM,Day1】工作流管理平台架构学习

    [课程主题] 主题:5天,一起从零开始学习BPM [课程形式] 1.为期5天的短任务学习 2.每天观看一个视频,视频学习时间自由安排. [第一天课程] Step 1 软件下载:H3 BPM10.0全开 ...

  9. Spark-shell和Spark-Submit的使用

    Spark-shell有两种使用方式: 1:直接Spark-shell 会启动一个SparkSubmit进程来模拟Spark运行环境,是一个单机版的. 2:Spark-shell --master S ...

  10. Linux环境下常见漏洞利用技术(培训ppt+实例+exp)

    记得以前在drops写过一篇文章叫 linux常见漏洞利用技术实践 ,现在还可以找得到(https://woo.49.gs/static/drops/binary-6521.html), 不过当时开始 ...