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); } 注意:千万要注意查询条件和数据库内的字段类型保持一致,否则将无法查找到数据。如:如果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<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 = 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<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", 10); b.Add("$lt", 20); 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", 10); b.Add("$lt", 20); query.Add("Uid", b); FieldsDocument f = new FieldsDocument(); f.Add("Name", 1); 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);//-1=DESC MongoCursor<Person> m = mongoCollection.FindAllAs<Person>().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);//小于等于<=  Query.Mod("value", 3, 1);//将查询值除以第一个给定值,若余数等于第二个给定值则返回该结果  Query.NE("name", "c");//不等于  Query.Nor(Array);//不包括数组中的值  Query.Not("name");//元素条件语句  Query.NotIn("name", "a", 2);//返回与数组中所有条件都不匹配的文档  Query.Or(Query.EQ("name", "a"), Query.EQ("title", "t"));//满足其中一个条件  Query.Size("name", 2);//给定键的长度  Query.Type("_id", BsonType.ObjectId );//给定键的类型  Query.Where(BsonJavaScript);//执行JavaScript  Query.Matches("Title",str);//模糊查询 相当于sql中like -- str可包含正则表达式
复制代码

 

 

 

 

 

 

 

在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 plain copy

/*---------------------------------------------* 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<Person> m = mongoCollection.FindAs<Person>(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<Person> m = mongoCollection.FindAs<Person>(query); 

 

public class News  {        public int _id { getset; }        public int count { getset; }        public string news { getset; }        public DateTime time { getset; }

}  MongoCursor<BsonDocument> allDoc = coll.FindAllAs<BsonDocument>(); BsonDocument doc = allDoc.First(); //BsonDocument类型参数  MongoCursor<News> allNews = coll.FindAllAs<News>();  News aNew = allNews.First(); //News类型参数  News firstNews = coll.FindOneAs<News>(); //查找第一个文档  QueryDocument query = new QueryDocument(); //定义查询文档 query.Add("_id"10001); query.Add("count"1); MongoCursor<News> qNews = coll.FindAs<News>(query);   BsonDocument bd = new BsonDocument();//定义查询文档 count>2 and count<=4 bd.Add("$gt"2); bd.Add("$lte"4); QueryDocument query_a = new QueryDocument(); query_a.Add("count",bd); FieldsDocument fd = new FieldsDocument(); fd.Add("_id"0);

fd.Add("count"1); fd.Add("time"1); MongoCursor<News> mNewss = coll.FindAs<News>(query_a).SetFields(fd);//只返回count和time var time = BsonDateTime.Create("2011/9/5 23:26:00"); BsonDocument db_t = new BsonDocument(); db_t.Add("$gt", time); QueryDocument qd_3 = new QueryDocument(); qd_3.Add("time", db_t); MongoCursor<News> mNews = coll.FindAs<News>(qd_3);//

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中使用MongoDB的示例代码有几个部分。首先,你需要引用MongoDB的命名空间,例如"using MongoDB.Driver;"。然后,你需要建立一个MongoDB的客户端和数据库连接。你可以使用连接字符串来指定连接参数,如服务器地址和数据库名称。连接字符串可以通过配置文件读取,也可以直接在代码中指定。接下来,你需要指定要操作的集合名称,获取该集合的引用。你可以使用查询条件来过滤集合中的文档,并使用Find方法获取满足条件的文档列表。最后,你可以遍历文档列表,并输出文档中的字段值。在示例代码中,输出的姓名和电话字段分别通过p["name"]和p["phone"]来获取。示例代码中还展示了一种插入文档的方法,使用InsertOneAsync方法将一个文档插入到集合中。关于连接方式的不同,你可以选择使用连接字符串来建立连接,也可以直接指定服务器地址和数据库名称。但无论使用哪种方式,你都需要确保连接参数的正确性和有效性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [1.C#操作MongoDB](https://blog.csdn.net/qq_34035956/article/details/125716599)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [在C#中使用MongoDB](https://blog.csdn.net/u011301348/article/details/89330590)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值