Mongodb-使用C#Drivers实现增删改查

1.回顾:上篇学习了Mongodb的基本命令学习

2.这篇将学习使用Mongodb的C# Drivers实现增删改查

3.准备:

    3.1 C# Drivers支持情况

                     

      面对现在的学习,我们还是使用 Version2.0版本,因为它支持全部的的.NET , 因为技术是越来越成熟的;


    3.2 .NET 平台对 Mongodb版本的支持情况如下 :全部支持

                     


     3.3 下载

            Mongdb C#驱动   和 确定你已经配置和安装好你的Mongodb,若下载不下来的话,可以 点我下载


4.使用 

      4.1 引用

        (1) 打开vs2012及vs2012 版本以上 (.NET FrameWork4.5),新建项目,什么项目都行,能够测试就行,这里         使用控制台应用程序,

        (2)引用 所有dll ;

                                           

      4.2 连接mongdb 

        在连接之前,保证你 打开了 mongodb 服务,若不记得怎么打开,请访问 :点击学习打开服务


5. 新建MongoDb操作工具类 

        花了1个小时,写的工具类,测试测试吧!封装好了 mongdb连接 ,增删改查和创建集合
<pre name="code" class="csharp">using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MongoDBDemo1
{
   public class Connection
    {
         //创建数据库连接
       MongoServerSettings setting = new MongoServerSettings();
       MongoServerAddress address =new MongoServerAddress("127.0.0.1", 27017);

       MongoServer server = null;
       string dbName=string.Empty;

       /// <summary>
       ///  得到连接
       /// </summary>
	  public Connection()
       {
           setting.Server = address;
           server = new MongoServer(setting);
       }

        /// <summary>
        /// 构造函数  获得 dbname
        /// </summary>
        /// <param name="dbname">数据库名称</param>
        public Connection(string dbname)
       {
           this.dbName = dbname;
           setting.Server = address;
           server = new MongoServer(setting);
       } 



		  /// <summary>
       /// 外部调用得到数据库
       /// </summary>
       /// <param name="dbName"></param>
       /// <returns></returns>
       public MongoDatabase getMongoDataBase(string dbName)
       {
           return server.GetDatabase(dbName);
       
       }
       /// <summary>
       /// 重载 得到数据库
       /// </summary>
       /// <returns></returns>
       public MongoDatabase getMongoDataBase()
       {
           return server.GetDatabase(dbName);
       
       }

       /// <summary>
       /// 创建集合
       /// </summary>
       /// <param name="colName">集合名字</param>
       /// <returns></returns>
       public bool createCollection(string colName) 
       {
           MongoDatabase db = this.getMongoDataBase();
           CommandResult result= db.CreateCollection(colName);
           if (result.Ok)
           {
               return true;
           }
           else 
           {
               return false;
           }
       }

		
       /// <summary>
       /// 外部调用
       /// </summary>
       /// <param name="colName">集合名称</param>
       /// <param name="db">数据库对象</param>
       /// <returns></returns>

       public MongoCollection<BsonDocument> getMongoColl(string colName,MongoDatabase db){
          return db.GetCollection(colName);
       }

       /// <summary>
       /// 内部使用
       /// </summary>
       /// <param name="colName">集合名称</param>
       /// <returns></returns>

       public MongoCollection<BsonDocument> getMongoColl(string colName){
          return this.getMongoDataBase().GetCollection(colName);
       }
 


        /// <summary>
       /// 查询操作
        /// </summary>
        /// <param name="colName">集合名词</param>
        /// <param name="query">条件</param>
        /// <returns></returns>
       public MongoCursor<BsonDocument> select(string colName,IMongoQuery query){

           MongoCollection<BsonDocument> mcoll=getMongoColl(colName);
           try
           {
               if (query == null)
               {
                   return mcoll.FindAll();
               }
               else
               {
                   return mcoll.Find(query);
               }
           }
           finally {
               this.mongoClose();
           }
           
       }


       /// <summary>
       /// 增加操作
       /// </summary>
       /// <param name="colName">集合名称</param>
       /// <param name="bson">单条数据</param>
       /// <returns></returns>
       public bool insert(string colName,BsonDocument bson) 
       {
           MongoCollection<BsonDocument> mcoll = getMongoColl(colName);
           try
           {
               mcoll.Insert(bson);
               return true;
           }
           catch
           {
               return false;
           }
           finally {
               this.mongoClose();
           }
       }

       /// <summary>
       /// 增加多条
       /// </summary>
       /// <param name="colName">集合名称</param>
       /// <param name="bsonlist">数据集合</param>
       /// <returns></returns>
       public bool insert(string colName, List<BsonDocument> bsonlist)
       {
           MongoCollection<BsonDocument> mcoll = getMongoColl(colName);
           try
           {
               foreach (BsonDocument bson in bsonlist)
               {
                   mcoll.Insert(bson);
               }
               return true;
           }
           catch
           {
               return false;
           }
           finally {
               this.mongoClose();
           
           }
       }

       /// <summary>
       /// 修改操作
       /// </summary>
       /// <param name="colName">集合名称</param>
       /// <param name="query">条件</param>
       /// <param name="upd">修改的内容</param>
       /// <returns></returns>
       public bool update(string colName, IMongoQuery query,IMongoUpdate upd)
       {
           MongoCollection<BsonDocument> mcoll = getMongoColl(colName);
           try
           {
               mcoll.Update(query, upd);
               return true;
           }
           catch
           {
               return false;
           }
           finally {
               this.mongoClose();
           }
       }

       /// <summary>
       /// 删除操作
       /// </summary>
       /// <param name="cloName">集合名称</param>
       /// <param name="query">条件</param>
       /// <param name="flag">是否为0 ,为0 则删除 满足条件的全部信息</param>
       /// <returns>false/true</returns>
       public bool delete(string cloName, IMongoQuery query,int flag) {
           MongoCollection<BsonDocument> mcol = this.getMongoColl(cloName);
           try
           {
               if (flag == 0)
               {
                   mcol.Remove(query, RemoveFlags.None);
               }
               else
               {
                   mcol.Remove(query, RemoveFlags.Single);
               }
               return true;
           }
           catch
           {
               return false;
           }
           finally {
               this.mongoClose();
           }
       }





       /// <summary>
       /// 关闭连接
       /// </summary>
       public void mongoClose(){
         server.Disconnect();
       }
    
   }

}
  


 
 

6.实现增删改查

  6.1 了解

     如果你看前面的在命令行下操作mongodb的话,就开始6.3吧!
 

  6.2 建立连接

         实例化 连接类,声明数据库名,和集合名!
            string dbname = "student";
            string colName = "yuan";
            Connection conn = new Connection(dbname);
  

  6.3 创建集合 

     调用创建方法
         bool type= conn.createCollection(colName);
            if (type)
            {
                Console.WriteLine("创建成功!");
            }
            else 
            {
                Console.WriteLine("创建失败!");
            }

            Console.ReadKey();

  6.4 插入单条信息

      BsonDocument bson = new BsonDocument("name","csdn");
            bool type= conn.insert(colName, bson);
            if (type)
            {
                Console.WriteLine("增加数据成功!");
            }
            else
            {
                Console.WriteLine("增加数据成功失败!");
            }

  6.5 插入多条信息

  Dictionary<string,string> dic=new Dictionary<string,string>();
            dic.Add("name","ming");
            dic.Add("age","23");
            dic.Add("collage","hpu");
            dic.Add("sno","31120907");

            Dictionary<string, string> dic1 = new Dictionary<string, string>();
            dic1.Add("name", "zhuo");
            dic1.Add("age", "10");
            dic1.Add("collage", "hpu");
            dic1.Add("sno", "31120908");

            List<BsonDocument> list = new List<BsonDocument>() { 
              new BsonDocument(dic),
              new BsonDocument(dic1)
            };

            bool type=conn.insert(colName, list);
            if (type)
            {
                Console.WriteLine("增加数据成功!");
            }
            else
            {
                Console.WriteLine("增加数据成功失败!");
            }
            Console.ReadKey();

  6.6 简单查询

     MongoCursor<BsonDocument> cursor = conn.select(colName, null);
            foreach (BsonDocument bson in cursor)
            {
                Console.WriteLine(bson.ToString());
            }
            Console.ReadKey();

   结果如下:
                        

   6.7 条件查询

    //条件查询
            QueryDocument query = new QueryDocument("collage", "hpu");
            MongoCursor<BsonDocument> cursor = conn.select(colName, query);
            foreach (BsonDocument bson in cursor)
            {
                Console.WriteLine(bson.ToString());
            }
            Console.ReadKey();

      结果如下:
                        

     6.8 修改操作

    QueryDocument query = new QueryDocument("name", "zhuo");
            Dictionary<string, string> dic1 = new Dictionary<string, string>();
            dic1.Add("name", "zhuo");
            dic1.Add("age", "23");
            dic1.Add("collage", "hpu");
            dic1.Add("sno", "31120908");
            UpdateDocument upd = new UpdateDocument(dic1);
            bool type = conn.update(colName, query, upd);
            if (type)
            {
                Console.WriteLine("修改数据成功!");
            }
            else
            {
                Console.WriteLine("修改数据失败!");
            }

            //查看修改信息
            QueryDocument query1 = new QueryDocument("name", "zhuo");
            MongoCursor<BsonDocument> cursor = conn.select(colName, query1);
            foreach (BsonDocument bson in cursor)
            {
                Console.WriteLine(bson.ToString());
            }

            Console.ReadKey();

  结果如下:
                     

    6.9 删除操作 


            //先查询下全部
            Console.WriteLine("我是全部");
            MongoCursor<BsonDocument> cursor = conn.select(colName, null);
            foreach (BsonDocument bson in cursor)
            {
                Console.WriteLine(bson.ToString());
            }

            //删除age等于23的
            QueryDocument query = new QueryDocument("age","23");
            //第三个参数 为0时删除满足条件的所有,为其他数字是,仅删除1条
            bool type=conn.delete(colName, query, 1);

            Console.WriteLine("我是删除后的!");
            MongoCursor<BsonDocument> cursor1 = conn.select(colName, null);
            foreach (BsonDocument bson in cursor1)
            {
                Console.WriteLine(bson.ToString());
            }

  效果图如下:

                               


 7.总结 :这里仅仅演示了简单的增删改查,后面,大量的条件查询,还行练习

 8.   demo 下载

    下篇 将学习 JAVA Driver的使用!

©️2020 CSDN 皮肤主题: 点我我会动 设计师:上身试试 返回首页