你的位置:首页 > 数据库

[数据库]C#操作MongoDB数据库方法


    本文利用MongoDB官方发布的C#驱动,封闭了对MongoDB数据库的增删改查访问方法。

    1、引用MongoDB for C# Driver

    从网上下载C#访问MongoDB的驱动,得到两个DLL:

  • MongoDB.Driver.dll
  • MongoDB.Bson.dll

    将它们引用到项目中。

    2、编写数据库访问帮助类

    编写MongoDB访问帮助类MongoDbHelper:

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using MongoDB.Bson; 5 using MongoDB.Driver; 6 using MongoDB.Driver.Builders; 7 using MongoDbTest.Models; 8  9 namespace MongoDbTest 10 { 11   /// <summary> 12   /// MongoDB帮助类 13   /// </summary> 14   internal static class MongoDbHepler 15   { 16     /// <summary> 17     /// 获取数据库实例对象 18     /// </summary> 19     /// <param name="connectionString">数据库连接串</param> 20     /// <param name="dbName">数据库名称</param> 21     /// <returns>数据库实例对象</returns> 22     private static MongoDatabase GetDatabase(string connectionString, string dbName) 23     { 24       var server = MongoServer.Create(connectionString); 25       return server.GetDatabase(dbName); 26     } 27  28     #region 新增 29  30     /// <summary> 31     /// 插入一条记录 32     /// </summary> 33     /// <typeparam name="T">数据类型</typeparam> 34     /// <param name="connectionString">数据库连接串</param> 35     /// <param name="dbName">数据名称</param> 36     /// <param name="collectionName">集合名称</param> 37     /// <param name="model">数据对象</param> 38     public static void Insert<T>(string connectionString, string dbName, string collectionName, T model) where T : EntityBase 39     { 40       if (model == null) 41       { 42         throw new ArgumentNullException("model", "待插入数据不能为空"); 43       } 44       var db = GetDatabase(connectionString, dbName); 45       var collection = db.GetCollection<T>(collectionName); 46       collection.Insert(model); 47     } 48  49     #endregion 50  51     #region 更新 52  53     /// <summary> 54     /// 更新数据 55     /// </summary> 56     /// <param name="connectionString">数据库连接串</param> 57     /// <param name="dbName">数据库名称</param> 58     /// <param name="collectionName">集合名称</param> 59     /// <param name="query">查询条件</param> 60     /// <param name="dictUpdate">更新字段</param> 61     public static void Update(string connectionString, string dbName, string collectionName, IMongoQuery query, Dictionary<string, BsonValue> dictUpdate) 62     { 63       var db = GetDatabase(connectionString, dbName); 64       var collection = db.GetCollection(collectionName); 65       var update = new UpdateBuilder(); 66       if (dictUpdate != null && dictUpdate.Count > 0) 67       { 68         foreach (var item in dictUpdate) 69         { 70           update.Set(item.Key, item.Value); 71         } 72       } 73       var d = collection.Update(query, update, UpdateFlags.Multi); 74     } 75  76     #endregion 77  78     #region 查询 79  80     /// <summary> 81     /// 根据ID获取数据对象 82     /// </summary> 83     /// <typeparam name="T">数据类型</typeparam> 84     /// <param name="connectionString">数据库连接串</param> 85     /// <param name="dbName">数据库名称</param> 86     /// <param name="collectionName">集合名称</param> 87     /// <param name="id">ID</param> 88     /// <returns>数据对象</returns> 89     public static T GetById<T>(string connectionString, string dbName, string collectionName, ObjectId id) 90       where T : EntityBase 91     { 92       var db = GetDatabase(connectionString, dbName); 93       var collection = db.GetCollection<T>(collectionName); 94       return collection.FindOneById(id); 95     } 96  97     /// <summary> 98     /// 根据查询条件获取一条数据 99     /// </summary>100     /// <typeparam name="T">数据类型</typeparam>101     /// <param name="connectionString">数据库连接串</param>102     /// <param name="dbName">数据库名称</param>103     /// <param name="collectionName">集合名称</param>104     /// <param name="query">查询条件</param>105     /// <returns>数据对象</returns>106     public static T GetOneByCondition<T>(string connectionString, string dbName, string collectionName, IMongoQuery query)107       where T : EntityBase108     {109       var db = GetDatabase(connectionString, dbName);110       var collection = db.GetCollection<T>(collectionName);111       return collection.FindOne(query);112     }113 114     /// <summary>115     /// 根据查询条件获取多条数据116     /// </summary>117     /// <typeparam name="T">数据类型</typeparam>118     /// <param name="connectionString">数据库连接串</param>119     /// <param name="dbName">数据库名称</param>120     /// <param name="collectionName">集合名称</param>121     /// <param name="query">查询条件</param>122     /// <returns>数据对象集合</returns>123     public static List<T> GetManyByCondition<T>(string connectionString, string dbName, string collectionName, IMongoQuery query)124       where T : EntityBase125     {126       var db = GetDatabase(connectionString, dbName);127       var collection = db.GetCollection<T>(collectionName);128       return collection.Find(query).ToList();129     }130 131     /// <summary>132     /// 根据集合中的所有数据133     /// </summary>134     /// <typeparam name="T">数据类型</typeparam>135     /// <param name="connectionString">数据库连接串</param>136     /// <param name="dbName">数据库名称</param>137     /// <param name="collectionName">集合名称</param>138     /// <returns>数据对象集合</returns>139     public static List<T> GetAll<T>(string connectionString, string dbName, string collectionName)140       where T : EntityBase141     {142       var db = GetDatabase(connectionString, dbName);143       var collection = db.GetCollection<T>(collectionName);144       return collection.FindAll().ToList();145     }146 147     #endregion148 149     #region 删除150 151     /// <summary>152     /// 删除集合中符合条件的数据153     /// </summary>154     /// <param name="connectionString">数据库连接串</param>155     /// <param name="dbName">数据库名称</param>156     /// <param name="collectionName">集合名称</param>157     /// <param name="query">查询条件</param>158     public static void DeleteByCondition(string connectionString, string dbName, string collectionName, IMongoQuery query)159     {160       var db = GetDatabase(connectionString, dbName);161       var collection = db.GetCollection(collectionName);162       collection.Remove(query);163     }164 165     /// <summary>166     /// 删除集合中的所有数据167     /// </summary>168     /// <param name="connectionString">数据库连接串</param>169     /// <param name="dbName">数据库名称</param>170     /// <param name="collectionName">集合名称</param>171     public static void DeleteAll(string connectionString, string dbName, string collectionName)172     {173       var db = GetDatabase(connectionString, dbName);174       var collection = db.GetCollection(collectionName);175       collection.RemoveAll();176     }177 178     #endregion179 180   }181 }

View Code

    3、编写测试类

    (1)配置数据库参数

    在配置文件中编写数据库连接串和数据库名称。

<??><configuration> <appSettings>  <!--MongoDB数据库连接串-->  <add key="MongoDBConn" value="mongodb://127.0.0.1:27017"/>  <!--MongoDB数据库名称-->  <add key="MongoDBName" value="mydb"/> </appSettings>   <startup>     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  </startup></configuration>

View Code

    将其写入C#代码中:

using System.Configuration;namespace MongoDbTest{  /// <summary>  /// 数据库配置参数  /// </summary>  internal static class DbConfigParams  {    private static string _conntionString = ConfigurationManager.AppSettings["MongoDBConn"];    /// <summary>    /// 获取 数据库连接串    /// </summary>    public static string ConntionString    {      get { return _conntionString; }    }    private static string _dbName = ConfigurationManager.AppSettings["MongoDBName"];    /// <summary>    /// 获取 数据库名称    /// </summary>    public static string DbName    {      get { return _dbName; }    }  }}

View Code

    另外,将集合名称写到C#代码中作为字符串常量:

namespace MongoDbTest{  public class CollectionNames  {    public const string User = "User";    public const string Student = "Student";  }}

View Code

    (2)编写实体类

    首先,编写实体基类,其中含有默认的Id:

using MongoDB.Bson;using MongoDB.Bson.Serialization.Attributes;namespace MongoDbTest.Models{  /// <summary>  /// 实体基类  /// </summary>  public class EntityBase  {    /// <summary>    /// 主键    /// </summary>    [BsonId]    public ObjectId Id { get; set; }  }}

View Code

    然后,编写实体类:

namespace MongoDbTest.Models{  /// <summary>  /// 学生类  /// </summary>  public class Student : EntityBase  {    /// <summary>    /// 获取 姓名    /// </summary>    public string Name { get; set; }    /// <summary>    /// 获取 年龄    /// </summary>    public int Age { get; set; }    /// <summary>    /// 获取 状态    /// </summary>    public State State { get; set; }  }}

View Code

    其中,State枚举类定义如下:

namespace MongoDbTest.Models{  /// <summary>  /// 状态  /// </summary>  public enum State  {    /// <summary>    /// 全部    /// </summary>    All = 0,    /// <summary>    /// 正常    /// </summary>    Normal = 1,    /// <summary>    /// 未使用    /// </summary>    Unused = 2,  }}

View Code

    (3)编写测试代码

    在主程序中编写测试代码:

 1 using System; 2 using System.Collections.Generic; 3 using MongoDB.Bson; 4 using MongoDB.Driver.Builders; 5 using MongoDbTest.Models; 6  7 namespace MongoDbTest 8 { 9   class Program 10   { 11     static void Main(string[] args) 12     { 13       Console.Title = "Mongo DB Test"; 14       InsertTest(); 15       //QueryTest(); 16       //UpdateTest(); 17       DeleteTest(); 18  19       Console.WriteLine("Finish!"); 20  21       Console.ReadLine(); 22     } 23  24     /// <summary> 25     /// 插入数据测试 26     /// </summary> 27     static void InsertTest() 28     { 29       var random = new Random(); 30       for (var i = 1; i <= 10; i++) 31       { 32         var item = new Student() 33         { 34           Name = "我的名字" + i, 35           Age = random.Next(25, 30), 36           State = i%2 == 0 ? State.Normal : State.Unused 37         }; 38         MongoDbHepler.Insert(DbConfigParams.ConntionString, DbConfigParams.DbName, CollectionNames.Student, item); 39       } 40     } 41  42     /// <summary> 43     /// 查询测试 44     /// </summary> 45     static void QueryTest() 46     { 47       var queryBuilder = new QueryBuilder<Student>(); 48       var query = queryBuilder.GTE(x => x.Age, 27); 49       var ltModel = MongoDbHepler.GetManyByCondition<Student>(DbConfigParams.ConntionString, DbConfigParams.DbName, 50         CollectionNames.Student, query); 51       if (ltModel != null && ltModel.Count > 0) 52       { 53         foreach (var item in ltModel) 54         { 55           Console.WriteLine("姓名:{0},年龄:{1},状态:{2}", 56             item.Name, item.Age, GetStateDesc(item.State)); 57         } 58       } 59     } 60  61     /// <summary> 62     /// 更新测试 63     /// </summary> 64     static void UpdateTest() 65     { 66       var queryBuilder = new QueryBuilder<Student>(); 67       var query = queryBuilder.GTE(x => x.Age, 27); 68       var dictUpdate = new Dictionary<string, BsonValue>(); 69       dictUpdate["State"] = State.Unused; 70       MongoDbHepler.Update(DbConfigParams.ConntionString, DbConfigParams.DbName, CollectionNames.Student, query, 71         dictUpdate); 72     } 73  74     /// <summary> 75     /// 删除测试 76     /// </summary> 77     static void DeleteTest() 78     { 79       var queryBuilder = new QueryBuilder<Student>(); 80       var query = queryBuilder.GTE(x => x.Age, 28); 81       MongoDbHepler.DeleteByCondition(DbConfigParams.ConntionString, DbConfigParams.DbName, CollectionNames.Student, query); 82     } 83  84     /// <summary> 85     /// 获取状态描述 86     /// </summary> 87     /// <param name="state">状态</param> 88     /// <returns>状态描述</returns> 89     static string GetStateDesc(State state) 90     { 91       string result = string.Empty; 92       switch (state) 93       { 94         case State.All: 95           result = "全部"; 96           break; 97         case State.Normal: 98           result = "正常"; 99           break;100         case State.Unused:101           result = "未使用";102           break;103         default:104           throw new ArgumentOutOfRangeException("state");105       }106       return result;107     }108   }109 }

View Code