序言

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. Python中的多进程与多线程(一)

    一.背景 最近在Azkaban的测试工作中,需要在测试环境下模拟线上的调度场景进行稳定性测试.故而重操python旧业,通过python编写脚本来构造类似线上的调度场景.在脚本编写过程中,碰到这样一个 ...

  2. 分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间)

    分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间) 很多时候我们都需要计算数据库中各个表的数据量和每行记录所占用空间 这里共享一个脚本 CREATE TABLE #tab ...

  3. LeetCode-3LongestSubstringWithoutRepeatingCharacters(C#)

    # 题目 3. Longest Substring Without Repeating Characters Given a string, find the length of the longes ...

  4. ASP.NET MVC5+EF6+EasyUI 后台管理系统(75)-微信公众平台开发-用户管理

    系列目录 前言 本节主要是关注者(即用户)和用户组的管理,微信公众号提供了用户和用户组的管理,我们可以在微信公众号官方里面进行操作,添加备注和标签,以及移动用户组别,同时,微信公众号也提供了相应的接口 ...

  5. ASP.NET Core 中文文档 第四章 MVC(4.2)控制器操作的路由

    原文:Routing to Controller Actions 作者:Ryan Nowak.Rick Anderson 翻译:娄宇(Lyrics) 校对:何镇汐.姚阿勇(Dr.Yao) ASP.NE ...

  6. JavaScript中String对象的方法介绍

    1.字符方法 1.1 charAt() 方法,返回字符串中指定位置的字符. var question = "Do you like JavaScript?"; alert(ques ...

  7. Linux程序包管理之rpm

    rpm简介 rpm( Red Hat Package Manager )是一个开放的软件包管理系统.它工作于Red Hat Linux及其他Linux系统,成为Linux中公认的软件包管理标准. rp ...

  8. Web前端需要熟悉大学里【高大上】的计算机专业课吗?

    作为一名刚刚大学毕业,进入新的学习阶段的研究生,我必须说大学的专业课非常重要!不管你信不信,事实就是如此! 一.大学学习的专业课非常重要,它决定了我们能走到什么高度 前端的发展非常快,我常常觉得刚刚关 ...

  9. Java中的进程和线程

     Java中的进程与线程 一:进程与线程 概述:几乎任何的操作系统都支持运行多个任务,通常一个任务就是一个程序,而一个程序就是一个进程.当一个进程运行时,内部可能包括多个顺序执行流,每个顺序执行流就是 ...

  10. 不得不知的CLR中的GC

    引言 GC 作为CLR的垃圾回收器,让程序员可以把更多的关注度放在业务上而不是垃圾回收(内存回收)上.其实很多语言也有类似的东东, 如Java也有JIT 等等 GC基本概念 垃圾回收机制的算法有好多种 ...