|
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);
}
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);
}
注意:千万要注意查询条件和数据库内的字段类型保持一致,否则将无法查找到数据。如:如果Sex是整型,一点要记得将值转换为整型。
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();
//查询指定查询条件的第一条数据,查询条件可缺省。 var result2 = col.FindOneAs();
//查询指定查询条件的全部数据 var result3 = col.FindAs(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 = 123, Name = "xixiNormal", PassWord = "111111" };
mongoCollection.Insert(o);
//对象插入 Person p = new Person { Uid = 124, Name = "xixiObject", PassWord = "222222" };
mongoCollection.Insert(p);
//BsonDocument 插入 BsonDocument b = new BsonDocument();
b.Add("Uid", 125);
b.Add("Name", "xixiBson");
b.Add("PassWord", "333333");
mongoCollection.Insert(b);
Console.ReadLine();
}
}
class Person {
public int Uid;
public string Name;
public string PassWord;
}
}
结果:

都是上述配置写的,程序会自动建立对应的库和集合。
下面的操作不上完整代码了:
/*---------------------------------------------
* sql : SELECT * FROM table
*---------------------------------------------
*/
MongoCursor p = mongoCollection.FindAllAs();
/*---------------------------------------------
* sql : SELECT * FROM table WHERE Uid > 10 AND Uid < 20
*---------------------------------------------
*/
QueryDocument query = new QueryDocument();
BsonDocument b = new BsonDocument();
b.Add("$gt", 10);
b.Add("$lt", 20);
query.Add("Uid", b);
MongoCursor m = mongoCollection.FindAs(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", 10);
b.Add("$lt", 20);
query.Add("Uid", b);
FieldsDocument f = new FieldsDocument();
f.Add("Name", 1);
MongoCursor m = mongoCollection.FindAs(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);//-1=DESC
MongoCursor m = mongoCollection.FindAllAs().SetSortOrder(s).SetSkip(10).SetLimit(10);
官方驱动查询:
Query.All("name", "a", "b");//通过多个元素来匹配数组
Query.And(Query.EQ("name", "a"), Query.EQ("title", "t"));//同时满足多个条件
Query.EQ("name", "a");//等于
Query.Exists("type", true);//判断键值是否存在
Query.GT("value", 2);//大于>
Query.GTE("value", 3);//大于等于>=
Query.In("name", "a", "b");//包括指定的所有值,可以指定不同类型的条件和值
Query.LT("value", 9);//小于<
Query.LTE("value", 8);//小于等于 x.Name == "xumingxiang");
//或者
//Users users = col.FindOne(new Document { { "Name", "xumingxiang" } }); users.Sex = "women";
col.Update(users, x => x.Sex == "man");
}
/// /// 删除数据
/// public void Delete()
{
var col = db.GetCollection();
col.Remove(x => x.Sex == "man");
////或者
////查出Name值为xumingxiang的第一条记录 //Users users = col.FindOne(x => x.Sex == "man");
//col.Remove(users);}
/// /// 查询数据
/// public void Query()
{
var col = db.GetCollection();
var query = new Document { { "Name", "xumingxiang" } };
//查询指定查询条件的全部数据 var result1 = col.Find(query);
//查询指定查询条件的第一条数据 var result2 = col.FindOne(query);
//查询全部集合里的数据 var result3 = col.FindAll();
}
QueryDocument 的常用查询:
[csharp] view plaincopy
/*---------------------------------------------* sql : SELECT * FROM table WHERE ConfigID > 5 AND ObjID = 1
*--------------------------------------------*/
QueryDocument query = new QueryDocument();
BsonDocument b = new BsonDocument();
b.Add("$gt", 5);
query.Add("ConfigID", b);
query.Add("ObjID", 1);
MongoCursor m = mongoCollection.FindAs(query);
/*---------------------------------------------
* sql : SELECT * FROM table WHERE ConfigID > 5 AND ConfigID < 10
*---------------------------------------------
*/
QueryDocument query = new QueryDocument();
BsonDocument b = new BsonDocument();
b.Add("$gt", 5);
b.Add("$lt", 10);
query.Add("ConfigID", b);
MongoCursor m = mongoCollection.FindAs(query);
public class News
{
public int _id { get; set; }
public int count { get; set; }
public string news { get; set; }
public DateTime time { get; set; }
}
MongoCursor allDoc = coll.FindAllAs();
BsonDocument doc = allDoc.First(); //BsonDocument类型参数
MongoCursor allNews = coll.FindAllAs();
News aNew = allNews.First(); //News类型参数
News firstNews = coll.FindOneAs(); //查找第一个文档
QueryDocument query = new QueryDocument(); //定义查询文档
query.Add("_id", 10001);
query.Add("count", 1);
MongoCursor qNews = coll.FindAs(query);
BsonDocument bd = new BsonDocument();//定义查询文档 count>2 and count |
|