封装对MongoDB数据库的增删改查访问方法(基于MongoDB官方发布的C#驱动)

时间:2022-04-22 15:08:33

本文利用MongoDB官方发布的C#驱动,封装了对MongoDB数据库的增删改查访问方法。
先用官方提供的mongo-csharp-driver ,当前版本为1.7.0.4714

编写数据库访问帮助类 MongoDbHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDbTest.Models; namespace MongoDbTest
{
/// <summary>
/// MongoDB帮助类
/// </summary>
internal static class MongoDbHelper
{
/// <summary>
/// 获取数据库实例对象
/// </summary>
/// <param name="connectionString">数据库连接串</param>
/// <param name="dbName">数据库名称</param>
/// <returns>数据库实例对象</returns>
private static MongoDatabase GetDatabase(string connectionString, string dbName)
{
//创建数据库链接
var server = new MongoClient(connectionString).GetServer();
//获得数据库实例对象
return server.GetDatabase(dbName);
} /// <summary>
/// 插入一条记录
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="connectionString">数据库连接串</param>
/// <param name="dbName">数据库名称</param>
/// <param name="collectionName">集合名称</param>
/// <param name="model">数据对象</param>
public static void Insert<T>(string connectionString, string dbName, string collectionName, T model) where T : EntityBase
{
if (model == null)
{
throw new ArgumentNullException("model", "待插入数据不能为空");
}
var db = GetDatabase(connectionString, dbName);
var collection = db.GetCollection<T>(collectionName);
collection.Insert(model);
} /// <summary>
/// 更新数据
/// </summary>
/// <param name="connectionString">数据库连接串</param>
/// <param name="dbName">数据库名称</param>
/// <param name="collectionName">集合名称</param>
/// <param name="query">查询条件</param>
/// <param name="dictUpdate">更新字段</param>
public static void Update(string connectionString, string dbName, string collectionName, IMongoQuery query, Dictionary<string, BsonValue> dictUpdate)
{
var db = GetDatabase(connectionString, dbName);
var collection = db.GetCollection(collectionName);
var update = new UpdateBuilder();
if (dictUpdate != null && dictUpdate.Count > )
{
foreach (var item in dictUpdate)
{
update.Set(item.Key, item.Value);
}
}
var d = collection.Update(query, update, UpdateFlags.Multi);
} /// <summary>
/// 根据ID获取数据对象
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="connectionString">数据库连接串</param>
/// <param name="dbName">数据库名称</param>
/// <param name="collectionName">集合名称</param>
/// <param name="id">ID</param>
/// <returns>数据对象</returns>
public static T GetById<T>(string connectionString, string dbName, string collectionName, ObjectId id)
where T : EntityBase
{
var db = GetDatabase(connectionString, dbName);
var collection = db.GetCollection<T>(collectionName);
return collection.FindOneById(id);
} /// <summary>
/// 根据查询条件获取一条数据
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="connectionString">数据库连接串</param>
/// <param name="dbName">数据库名称</param>
/// <param name="collectionName">集合名称</param>
/// <param name="query">查询条件</param>
/// <returns>数据对象</returns>
public static T GetOneByCondition<T>(string connectionString, string dbName, string collectionName, IMongoQuery query)
where T : EntityBase
{
var db = GetDatabase(connectionString, dbName);
var collection = db.GetCollection<T>(collectionName);
return collection.FindOne(query);
} /// <summary>
/// 根据查询条件获取多条数据
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="connectionString">数据库连接串</param>
/// <param name="dbName">数据库名称</param>
/// <param name="collectionName">集合名称</param>
/// <param name="query">查询条件</param>
/// <returns>数据对象集合</returns>
public static List<T> GetManyByCondition<T>(string connectionString, string dbName, string collectionName, IMongoQuery query)
where T : EntityBase
{
var db = GetDatabase(connectionString, dbName);
var collection = db.GetCollection<T>(collectionName);
return collection.Find(query).ToList();
} /// <summary>
/// 根据集合中的所有数据
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="connectionString">数据库连接串</param>
/// <param name="dbName">数据库名称</param>
/// <param name="collectionName">集合名称</param>
/// <returns>数据对象集合</returns>
public static List<T> GetAll<T>(string connectionString, string dbName, string collectionName)
where T : EntityBase
{
var db = GetDatabase(connectionString, dbName);
var collection = db.GetCollection<T>(collectionName);
return collection.FindAll().ToList();
} /// <summary>
/// 删除集合中符合条件的数据
/// </summary>
/// <param name="connectionString">数据库连接串</param>
/// <param name="dbName">数据库名称</param>
/// <param name="collectionName">集合名称</param>
/// <param name="query">查询条件</param>
public static void DeleteByCondition(string connectionString, string dbName, string collectionName, IMongoQuery query)
{
var db = GetDatabase(connectionString, dbName);
var collection = db.GetCollection(collectionName);
collection.Remove(query);
} /// <summary>
/// 删除集合中的所有数据
/// </summary>
/// <param name="connectionString">数据库连接串</param>
/// <param name="dbName">数据库名称</param>
/// <param name="collectionName">集合名称</param>
public static void DeleteAll(string connectionString, string dbName, string collectionName)
{
var db = GetDatabase(connectionString, dbName);
var collection = db.GetCollection(collectionName);
collection.RemoveAll();
} }
}

数据库配置参数 DbConfigParams.cs

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; }
} } }

将集合名称写到C#代码中作为字符串常量 CollectionNames.cs

namespace MongoDbTest
{
/// <summary>
/// 将集合名称写到C#代码中作为字符串常量
/// </summary>
public class CollectionNames
{
public const string User = "User";
public const string Role = "Role";
}
}

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

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!--MongoDB数据库连接串-->
<add key="MongoDBConn" value="mongodb://127.0.0.1:27017"/>
<!--MongoDB数据库名称-->
<add key="MongoDBName" value="RsdfDb"/>
</appSettings>
</configuration>

编写实体基类,其中含有默认的Id EntityBase.cs

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

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

namespace MongoDbTest.Models
{
public enum State
{
/// <summary>
/// 正常
/// </summary>
Normal = ,
/// <summary>
/// 未使用
/// </summary>
Unused = ,
}
}

编写实体类 User.cs

namespace MongoDbTest.Models
{
public class User : EntityBase
{
public string UserName { get; set; }
public int Age { get; set; }
public State State { get; set; }
}
}

编写测试类

using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using MongoDbTest.Models; namespace MongoDbTest
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Mongo DB Test";
//InsertTest();
//QueryTest();
//UpdateTest();
DeleteTest(); Console.WriteLine("Finish!"); Console.ReadLine();
} /// <summary>
/// 插入数据测试
/// </summary>
static void InsertTest()
{
var random = new Random();
for (var i = ; i <= ; i++)
{
var item = new User()
{
UserName = "我的名字" + i,
Age = random.Next(, ),
State = i % == ? State.Normal : State.Unused
};
MongoDbHelper.Insert(DbConfigParams.ConntionString, DbConfigParams.DbName, CollectionNames.User, item);
}
} /// <summary>
/// 查询测试
/// </summary>
static void QueryTest()
{
var queryBuilder = new QueryBuilder<User>();
var query = queryBuilder.GTE(x => x.Age, );
var ltModel = MongoDbHelper.GetManyByCondition<User>(DbConfigParams.ConntionString, DbConfigParams.DbName,
CollectionNames.User, query);
if (ltModel != null && ltModel.Count > )
{
foreach (var item in ltModel)
{
Console.WriteLine("姓名:{0},年龄:{1},状态:{2}",
item.UserName, item.Age, GetStateDesc(item.State));
}
}
} /// <summary>
/// 更新测试
/// </summary>
static void UpdateTest()
{
var queryBuilder = new QueryBuilder<User>();
var query = queryBuilder.GTE(x => x.Age, );
var dictUpdate = new Dictionary<string, BsonValue>();
dictUpdate["State"] = State.Unused;
MongoDbHelper.Update(DbConfigParams.ConntionString, DbConfigParams.DbName, CollectionNames.User, query,
dictUpdate);
} /// <summary>
/// 删除测试
/// </summary>
static void DeleteTest()
{
var queryBuilder = new QueryBuilder<User>();
var query = queryBuilder.GTE(x => x.Age, );
MongoDbHelper.DeleteByCondition(DbConfigParams.ConntionString, DbConfigParams.DbName, CollectionNames.User, query);
} /// <summary>
/// 获取状态描述
/// </summary>
/// <param name="state">状态</param>
/// <returns>状态描述</returns>
static string GetStateDesc(State state)
{
string result = string.Empty;
switch (state)
{
case State.Normal:
result = "正常";
break;
case State.Unused:
result = "未使用";
break;
default:
throw new ArgumentOutOfRangeException("state");
}
return result;
} }
}

测试结果:

封装对MongoDB数据库的增删改查访问方法(基于MongoDB官方发布的C#驱动)