在C#中使用官方驱动操作MongoDB

8.1)下载安装

想要在C#中使用MongoDB,首先得要有个MongoDB支持的C#版的驱动。C#版的驱动有很多种,如官方提供的,samus。 实现思路大都类似。这里我们先用官方提供的mongo-csharp-driver ,当前版本为1.4.1

下载地址:http://github.com/mongodb/mongo-csharp-driver/downloads

编译之后得到两个dll

MongoDB.Driver.dll:顾名思义,驱动程序

MongoDB.Bson.dll:序列化、Json相关

然后在我们的程序中引用这两个dll。

下面的部分简单演示了怎样使用C#对MongoDB进行增删改查操作。

8.2)连接数据库:

在连接数据库之前请先确认您的MongoDB已经开启了。

//数据库连接字符串 const string strconn = "mongodb://127.0.0.1:27017";
//数据库名称 const string dbName = "cnblogs";
//创建数据库链接 MongoServer server = MongoDB.Driver.MongoServer.Create(strconn);
//获得数据库cnblogs MongoDatabase db = server.GetDatabase(dbName);

8.3)插入数据:

好了数据打开了,现在得添加数据了,我们要添加一条User“记录”到 Users集合中。

在MongoDB中没有表的概念,所以在插入数据之前不需要创建表。

但我们得定义好要插入的数据的模型Users

Users.cs:
public class Users
{
public ObjectId _id;//BsonType.ObjectId 这个对应了 MongoDB.Bson.ObjectId     public string Name { get; set; }
public string Sex { set; get; }
}

_id 属性必须要有,否则在更新数据时会报错:“Element '_id' does not match any field or property of class”。

好,现在看看添加数据的代码怎么写:

public void Insert()
{
//创建数据库链接 MongoServer server = MongoDB.Driver.MongoServer.Create(strconn);
//获得数据库cnblogs MongoDatabase db = server.GetDatabase(dbName);
Users users = new Users();
users.Name = "xumingxiang";
users.Sex = "man";
//获得Users集合,如果数据库中没有,先新建一个 MongoCollection col = db.GetCollection("Users");
//执行插入操作 col.Insert<Users>(users);
}

8.4)更新数据

public void Update()
{
//创建数据库链接 MongoServer server = MongoDB.Driver.MongoServer.Create(strconn);
//获得数据库cnblogs MongoDatabase db = server.GetDatabase(dbName);
//获取Users集合 MongoCollection col = db.GetCollection("Users");
//定义获取“Name”值为“xumingxiang”的查询条件 var query = new QueryDocument { { "Name", "xumingxiang" } };
//定义更新文档 var update = new UpdateDocument { { "$set", new QueryDocument { { "Sex", "wowen" } } } };
//执行更新操作 col.Update(query, update);
}

8.5)删除数据

public void Delete()
{
//创建数据库链接 MongoServer server = MongoDB.Driver.MongoServer.Create(strconn);
//获得数据库cnblogs MongoDatabase db = server.GetDatabase(dbName);
//获取Users集合 MongoCollection col = db.GetCollection("Users");
//定义获取“Name”值为“xumingxiang”的查询条件 var query = new QueryDocument { { "Name", "xumingxiang" } };
//执行删除操作 col.Remove(query);
}

8.6)查询数据

public void Query()
{
//创建数据库链接 MongoServer server = MongoDB.Driver.MongoServer.Create(strconn);
//获得数据库cnblogs MongoDatabase db = server.GetDatabase(dbName);
//获取Users集合 MongoCollection col = db.GetCollection("Users");
//定义获取“Name”值为“xumingxiang”的查询条件 var query = new QueryDocument { { "Name", "xumingxiang" } }; //查询全部集合里的数据 var result1 = col.FindAllAs<Users>();
//查询指定查询条件的第一条数据,查询条件可缺省。 var result2 = col.FindOneAs<Users>();
//查询指定查询条件的全部数据 var result3 = col.FindAs<Users>(query);
}

MongoDb在C#中使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Data;
using System.Data.SqlClient;
using MongoDB.Bson;
using MongoDB.Driver; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//连接信息 string conn = "mongodb://localhost";
string database = "demoBase";
string collection = "demoCollection"; MongoServer mongodb = MongoServer.Create(conn);//连接数据库 MongoDatabase mongoDataBase = mongodb.GetDatabase(database);//选择数据库名 MongoCollection mongoCollection = mongoDataBase.GetCollection(collection);//选择集合,相当于表
mongodb.Connect(); //普通插入 var o = new { Uid = , Name = "xixiNormal", PassWord = "" };
mongoCollection.Insert(o); //对象插入 Person p = new Person { Uid = , Name = "xixiObject", PassWord = "" };
mongoCollection.Insert(p); //BsonDocument 插入 BsonDocument b = new BsonDocument();
b.Add("Uid", );
b.Add("Name", "xixiBson");
b.Add("PassWord", "");
mongoCollection.Insert(b); Console.ReadLine();
}
} class Person {
public int Uid;
public string Name;
public string PassWord; }
}

结果:

都是上述配置写的,程序会自动建立对应的库和集合。

下面的操作不上完整代码了:

            /*---------------------------------------------
* sql : SELECT * FROM table
*---------------------------------------------
*/
MongoCursor<Person> p = mongoCollection.FindAllAs<Person>(); /*---------------------------------------------
* sql : SELECT * FROM table WHERE Uid > 10 AND Uid < 20
*---------------------------------------------
*/
QueryDocument query = new QueryDocument();
BsonDocument b = new BsonDocument();
b.Add("$gt", );
b.Add("$lt", );
query.Add("Uid", b); MongoCursor<Person> m = mongoCollection.FindAs<Person>(query); /*-----------------------------------------------
* sql : SELECT COUNT(*) FROM table WHERE Uid > 10 AND Uid < 20
*-----------------------------------------------
*/
long c = mongoCollection.Count(query); /*-----------------------------------------------
* sql : SELECT Name FROM table WHERE Uid > 10 AND Uid < 20
*-----------------------------------------------
*/
QueryDocument query = new QueryDocument();
BsonDocument b = new BsonDocument();
b.Add("$gt", );
b.Add("$lt", );
query.Add("Uid", b);
FieldsDocument f = new FieldsDocument();
f.Add("Name", ); MongoCursor<Person> m = mongoCollection.FindAs<Person>(query).SetFields(f);
/*-----------------------------------------------
* sql : SELECT * FROM table ORDER BY Uid DESC LIMIT 10,10
*-----------------------------------------------
*/
QueryDocument query = new QueryDocument();
SortByDocument s = new SortByDocument();
s.Add("Uid", -);//-1=DESC
MongoCursor<Person> m = mongoCollection.FindAllAs<Person>().SetSortOrder(s).SetSkip().SetLimit();

在C#中使用samus驱动操作MongoDB

再来介绍一款第三方驱动samus,这是一款使用使用较多的驱动,更新频率比较快,samus驱动除了支持一般形式的操作之外,还支持Linq 和Lambda 表达式。

下载地址:https://github.com/samus/mongodb-csharp

下载回来编译得到两个dll

MongoDB.dll          驱动的主要程序

MongoDB.GridFS.dll    用于存储大文件。

这里我们引用MongoDB.dll  即可。关于MongoDB.GridFS.dll 本文用不到,暂不介绍,无视它。

其连接数据库以及CRUD操作如下:

//数据库连接字符串const string strconn = "mongodb://127.0.0.1:27017";
//数据库名称const string dbName = "cnblogs";
//定义数据库MongoDatabase db; /// <summary>/// 打开数据库链接
/// </summary>public void GetConnection()
{
//定义Mongo服务 Mongo mongo = new Mongo(strconn);
//打开连接 mongo.Connect();
//获得数据库cnblogs,若不存在则自动创建 db = mongo.GetDatabase(dbName) as MongoDatabase;
} /// <summary>/// 添加数据
/// </summary>public void Insert()
{
var col = db.GetCollection<Users>();
//或者
//var col = db.GetCollection("Users");
Users users = new Users();
users.Name = "xumingxiang";
users.Sex = "man";
col.Insert(users);
}
/// <summary>/// 更新数据
/// </summary>public void Update()
{
var col = db.GetCollection<Users>();
//查出Name值为xumingxiang的第一条记录 Users users = col.FindOne(x => x.Name == "xumingxiang");
//或者
//Users users = col.FindOne(new Document { { "Name", "xumingxiang" } }); users.Sex = "women";
col.Update(users, x => x.Sex == "man");
} /// <summary>/// 删除数据
/// </summary>public void Delete()
{
var col = db.GetCollection<Users>();
col.Remove(x => x.Sex == "man");
////或者
////查出Name值为xumingxiang的第一条记录 //Users users = col.FindOne(x => x.Sex == "man");
//col.Remove(users);} /// <summary>/// 查询数据
/// </summary>public void Query()
{
var col = db.GetCollection<Users>();
var query = new Document { { "Name", "xumingxiang" } }; //查询指定查询条件的全部数据 var result1 = col.Find(query);
//查询指定查询条件的第一条数据 var result2 = col.FindOne(query);
//查询全部集合里的数据 var result3 = col.FindAll();
}

QueryDocument 的常用查询:

[csharp] view plaincopy

  1. /*---------------------------------------------
  2. * sql : SELECT * FROM table WHERE ConfigID > 5 AND ObjID = 1
  3. *---------------------------------------------
  4. */
  5. QueryDocument query = new QueryDocument();
  6. BsonDocument b = new BsonDocument();
  7. b.Add("$gt", 5);
  8. query.Add("ConfigID", b);
  9. query.Add("ObjID", 1);
  10. MongoCursor<Person> m = mongoCollection.FindAs<Person>(query);
  11. /*---------------------------------------------
  12. * sql : SELECT * FROM table WHERE ConfigID > 5 AND ConfigID < 10
  13. *---------------------------------------------
  14. */
  15. QueryDocument query = new QueryDocument();
  16. BsonDocument b = new BsonDocument();
  17. b.Add("$gt", 5);
  18. b.Add("$lt", 10);
  19. query.Add("ConfigID", b);
  20. MongoCursor<Person> m = mongoCollection.FindAs<Person>(query);

1     public class News  2     {  3         public int _id { get; set; }  4         public int count { get; set; }  5         public string news { get; set; }  6         public DateTime time { get; set; }  7     }  8  9 MongoCursor<BsonDocument> allDoc = coll.FindAllAs<BsonDocument>(); 10 BsonDocument doc = allDoc.First(); //BsonDocument类型参数11 12 MongoCursor<News> allNews = coll.FindAllAs<News>(); 13 News aNew = allNews.First(); //News类型参数14 15 News firstNews = coll.FindOneAs<News>(); //查找第一个文档16 17 QueryDocument query = new QueryDocument(); //定义查询文档18 query.Add("_id", 10001); 19 query.Add("count", 1); 20 MongoCursor<News> qNews = coll.FindAs<News>(query); 21 22 23 BsonDocument bd = new BsonDocument();//定义查询文档 count>2 and count<=424 bd.Add("$gt", 2); 25 bd.Add("$lte", 4); 26 QueryDocument query_a = new QueryDocument(); 27 query_a.Add("count",bd); 28 29 FieldsDocument fd = new FieldsDocument(); 30 fd.Add("_id", 0); 31 fd.Add("count", 1); 32 fd.Add("time", 1); 33 34 MongoCursor<News> mNewss = coll.FindAs<News>(query_a).SetFields(fd);//只返回count和time35 36 var time = BsonDateTime.Create("2011/9/5 23:26:00"); 37 BsonDocument db_t = new BsonDocument(); 38 db_t.Add("$gt", time); 39 QueryDocument qd_3 = new QueryDocument(); 40 qd_3.Add("time", db_t); 41 42 MongoCursor<News> mNews = coll.FindAs<News>(qd_3);//

[转载]在C#中使用官方驱动操作MongoDB的更多相关文章

  1. C#中使用官方驱动操作MongoDB

    想要在C#中使用MongoDB,首先得要有个MongoDB支持的C#版的驱动.C#版的驱动有很多种,如官方提供的,samus. 实现思路大都类似.这里我们先用官方提供的mongo-csharp-dri ...

  2. 在C#中使用官方驱动操作MongoDB

    MongoDB的官方驱动下载地址:https://github.com/mongodb/mongo-csharp-driver/releases 目前最新的版本是2.10,支持.NET 4.5以上.由 ...

  3. 在C#中使用官方驱动操作MongoDB ---转载

    http://blog.csdn.net/dannywj1371/article/details/7440916

  4. C#/.NET 使用官方驱动操作MongoDB(一):插入、查询

    概述 想要在C#中使用MongoDB,首先得要有个MongoDB支持的C#版的驱动. C#版的驱动有很多,这里我们先用官方提供的 MongoDB.Driver(使用 Nuget 安装),当前版本为2. ...

  5. 使用MongoDB C#官方驱动操作MongoDB

    想要在C#中使用MongoDB,首先得要有个MongoDB支持的C#版的驱动.C#版的驱动有很多种,如官方提供的,samus. 实现思路大都类似.这里我们先用官方提供的mongo-csharp-dri ...

  6. MongoDB学习-->命令行增删改查&JAVA驱动操作Mongodb

    MongoDB 是一个基于分布式文件存储的数据库. 由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关 ...

  7. MongoDB基础入门003--使用官方驱动操作mongo,C#

    本篇先简单介绍一下,使用官方驱动来操作MongoDB.至于MongoDB原生的增删改查语句,且等以后再慢慢学习. 一.操作MongoDB的驱动主要有两个 1.官方驱动:https://github.c ...

  8. 使用Mongo官方驱动操作Mongo数据库

    首先到 https://github.com/mongodb/mongo-csharp-driver/downloads 下载Mongo官方驱动 下载完成后引用到项目中 public class Co ...

  9. 基于官方驱动封装mongodb

    还是一如既往先把结构图放出来,上上个版本添加了redis的缓存,但是不满足我的需求,因为公司有项目要求是分布式所以呢,这里我就增加了mongoDb进行缓存分布式,好了先看结构图(1). 总的来说比较蛋 ...

随机推荐

  1. Python 基础【第五篇】元组和列表

    一 .Python之列表: 其实所谓的列表我个人感觉和shell 中的数组是一样的(只是个人见解哦),列表其实说白了就是元素的组合: 格式: Name = [a,b,c,d] 下标: 每一个列表中的元 ...

  2. bvp4c--语法

    bvp4c--语法   1. bvp4c: sol = bvp4c(odefun,bcfun,solinit) sol = bvp4c(odefun,bcfun,solinit,options) so ...

  3. HTTP层 —— 控制器

    1.简介 将所有的请求处理逻辑都放在单个 routes.php 中显然是不合理的,你也许还希望使用控制器类组织管理这些行为.控制器可以将相关的 HTTP 请求封装到一个类中进行处理.通常控制器存放在 ...

  4. 跨站脚本攻击(XSS)

    跨站脚本攻击(XSS) XSS发生在目标网站中目标用户的浏览器层面上,当用户浏览器渲染整个HTML文档的过程中就出现了不被预期的脚本执行. 跨站脚本的重点不是在“跨站”上,而应该在“脚本上” 简单例子 ...

  5. 关于async和await的一些误区实例详解

    转载自 http://www.jb51.net/article/53399.htm 这篇文章主要介绍了关于async和await的一些误区实例详解,有助于更加深入的理解C#程序设计,需要的朋友可以参考 ...

  6. SQL Server 错误检测与修复

    简介 在一个理想的世界中,不会存在任何数据库的损坏,就像我们不会将一些严重意外情况列入我们生活中的日常一样,而一旦这类事情发生,一定会对我们的生活造成非常显著的影响,在SQL Server中也同样如此 ...

  7. iOS-学习路线图(推荐)

    在学习一个新的知识时,除了保持积极的态度.对知识的渴望,学习路线以及方法也是很重要的.在学习iOS的时候,遇到这样的情况,非常想去学习,提高,但是没有一个学习路线,不知道从哪里入手,该先学什么.在学什 ...

  8. 【原创】关于MVC自己新建的 action,Controller提示找不到页面的问题

    一.实例: 1.比如我自己新建了一个~/view/Shop  文件夹下的IndexShop.aspx,那么在Controllers文件夹下就要对应一个ShopController.cs的Control ...

  9. 03链栈_LinkStack--(栈与队列)

    #include "stdio.h" #include "stdlib.h" #include "io.h" #include " ...

  10. HDU 2993 MAX Average Problem(斜率优化DP)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2993 题目大意:给定一个长度为n(最长为10^5)的正整数序列,求出连续的最短为k的子序列平均值的最大 ...