zoukankan      html  css  js  c++  java
  • [转载]在C#中使用官方驱动操作MongoDB

    在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 = 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);

     

     

     

     

     

     

     

    在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. /*---------------------------------------------             
    13. * sql : SELECT * FROM table WHERE ConfigID > 5 AND ConfigID < 10            
    14. *---------------------------------------------              
    15. */              
    16. QueryDocument query = new QueryDocument();              
    17. BsonDocument b = new BsonDocument();              
    18. b.Add("$gt", 5);     
    19. b.Add("$lt", 10);                   
    20. query.Add("ConfigID", b);  
    21. MongoCursor<Person> m = mongoCollection.FindAs<Person>(query);  

     

     

     

     1     public class News  2     {  3         public int _id { getset; }  4         public int count { getset; }  5         public string news { getset; }  6         public DateTime time { getset; }  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);//

  • 相关阅读:
    make menuconfig出现乱码
    内存中的变量和值
    is&==
    python小整数池
    生成器
    GIL
    grub rescue问题修复
    期末考试
    期末要求
    选课练习
  • 原文地址:https://www.cnblogs.com/iack/p/3537935.html
Copyright © 2011-2022 走看看