一.背景

公司项目中在做数据存储时使用到Mongodb,所以想着将Mongodb的操作封装后可供项目中其他成员方便使用。

附上Mongodb的下载地址: 下载

1.Mongodb类 此类主要是用来构造Mongodb数据库实例的。

 public class MongoDb
{
public MongoDb(string host, string DbName, string timeOut)
{
this.Connect_TimeOut = timeOut;
this.Mongo_Conn_Host = host;
this.Db_Name = DbName;
}
/// <summary>
/// 数据库所在主机
/// </summary>
private readonly string Mongo_Conn_Host;
/// <summary>
/// 数据库所在主机的端口
/// </summary>
private readonly int Mongo_Conn_Port = 27017;
//private readonly int Mongo_Conn_Port = 8635;
/// <summary>
/// 连接超时设置 秒
/// </summary>
private readonly string Connect_TimeOut; /// <summary>
/// 数据库名称
/// </summary>
private readonly string Db_Name; /// <summary>
/// 得到数据库实例
/// </summary>
/// <returns></returns>
public IMongoDatabase GetDataBase()
{ MongoClientSettings mongoSetting = new MongoClientSettings();
//设置连接超时时间
//mongoSetting.ConnectTimeout = new TimeSpan(int.Parse(Connect_TimeOut) * TimeSpan.TicksPerSecond);
mongoSetting.ConnectTimeout = TimeSpan.FromSeconds(1000);
//设置数据库服务器
mongoSetting.Server = new MongoServerAddress(Mongo_Conn_Host, Mongo_Conn_Port); //创建Mongo的客户端
MongoClient client = new MongoClient(mongoSetting);
//得到服务器端并且生成数据库实例
return client.GetDatabase(Db_Name);
}
}

2.MongoEntityBase类 包含Mongodb的主键 _id

    public class MongoEntityBase
{
public ObjectId _id { get; set; } }

3.MongodbConfig类,包含Mongodb的连接地址,数据库名称和集合名称

    public class MongoDBConfig
{
public string ConnectionString { get; set; }
public string DbName { get; set; }
public string CollectionName { get; set; }
}

4.MongodbRepository泛型类,传入要操作的对象实现CRUD

  public class MongoDbRepository<T>where T : MongoEntityBase
{
public IMongoCollection<T> Collection { get; private set; }
public IMongoDatabase Database { get; private set; } public MongoDbRepository(MongoDBConfig config)
{
Database = new MongoClient(config.ConnectionString).GetDatabase(config.DbName);
Collection = Database.GetCollection<T>(config.CollectionName);
}
#region +Add 添加一条数据
public void Add(T t)
{
try
{
this.Collection.InsertOne(t);
}
catch (Exception e)
{ throw e;
}
}
#endregion #region +AddAsync 异步添加一条数据
/// <summary>
/// 异步添加一条数据
/// </summary>
/// <param name="t">添加的实体</param>
/// <param name="host">mongodb连接信息</param>
/// <returns></returns>
public async Task AddAsync(T t)
{
try
{
await Collection.InsertOneAsync(t);
}
catch (Exception e)
{
throw e;
}
}
#endregion #region +InsertMany 批量插入
/// <summary>
/// 批量插入
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="t">实体集合</param>
/// <returns></returns>
public void InsertMany(List<T> t)
{
try
{
if (t != null && t.Count > )
{
Collection.InsertMany(t);
}
}
catch (Exception ex)
{
throw new UserFriendlyException(ex.Message);
}
}
public async Task InsertManyAsync(List<T> t)
{
try
{
if (t != null && t.Count > )
{
await Collection.InsertManyAsync(t);
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region +Update 修改一条数据
/// <summary>
/// 修改一条数据
/// </summary>
/// <param name="t">添加的实体</param>
/// <param name="host">mongodb连接信息</param>
/// <returns></returns>
public ReplaceOneResult UpdateOne(T t)
{
try
{
//修改条件
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", t._id);
//Collection.UpdateOne(filter,Builders<T>.Update)
return Collection.ReplaceOne(filter, t, new UpdateOptions { IsUpsert = true });
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region +UpdateManay 批量修改数据
/// <summary>
/// 批量修改数据
/// </summary>
/// <param name="dic">要修改的字段</param>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">修改条件</param>
/// <returns></returns>
public UpdateResult UpdateManay(Expression<Func<T, bool>> filter, dynamic modifyFields)
{
try
{
var list = new List<UpdateDefinition<T>>();
foreach (PropertyInfo item in modifyFields.GetType().GetProperties())
{
if (item.Name.ToLower() == "id") continue;
list.Add(Builders<T>.Update.Set(item.Name, item.GetValue(modifyFields)));
}
return Collection.UpdateMany(filter, Builders<T>.Update.Combine(list));
}
catch (Exception ex)
{
throw new UserFriendlyException(ex.Message);
}
}
#endregion #region Delete 删除一条数据
/// <summary>
/// 删除一条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="id">objectId</param>
/// <returns></returns>
public DeleteResult DeleteOne(ObjectId id)
{
try
{
var filter = Builders<T>.Filter.Eq("_id", id);
return Collection.DeleteOne(filter);
}
catch (Exception ex)
{
throw ex;
} }
/// <summary>
/// 删除一条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">删除条件</param>
/// <returns></returns>
public DeleteResult DeleteMany(Expression<Func<T, bool>> filter)
{
try
{
return Collection.DeleteMany(filter);
}
catch (Exception ex)
{
throw ex;
} }
#endregion #region Count 根据条件获取总数
/// <summary>
/// 根据条件获取总数
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">条件</param>
/// <returns></returns>
public long Count(Expression<Func<T, bool>> filter)
{
try
{
return Collection.CountDocuments(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region FindOne 根据id查询一条数据
/// <summary>
/// 根据id查询一条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="id">objectid</param>
/// <param name="field">要查询的字段,不写时查询全部</param>
/// <returns></returns>
public T FindOne(ObjectId id)
{
try
{
return Collection.Find(x => x._id == id).FirstOrDefault<T>();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region FindList 查询集合
/// <summary>
/// 查询集合
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">查询条件</param>
/// <param name="field">要查询的字段,不写时查询全部</param>
/// <param name="sort">要排序的字段</param>
/// <returns></returns>
public List<U> FindList<U>(Expression<Func<T, bool>> exp, Expression<Func<T, U>> select)
{
try
{
return Collection.AsQueryable().Where(exp).Select(select).ToList();
}
catch (Exception ex)
{
throw new UserFriendlyException(ex.Message);
}
}
public List<T> FindList(Expression<Func<T, bool>> exp)
{
try
{
return Collection.AsQueryable().Where(exp).ToList();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region FindListByPage 分页查询集合
/// <summary>
/// 分页查询集合
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">查询条件</param>
/// <param name="pageIndex">当前页</param>
/// <param name="pageSize">页容量</param>
/// <param name="count">总条数</param>
/// <param name="field">要查询的字段,不写时查询全部</param>
/// <param name="sort">要排序的字段</param>
/// <returns></returns>
public List<U> FindListByPage<U>(string field, string dir, Expression<Func<T, bool>> filter, int SkipCount, int pageSize, out long count, Expression<Func<T, U>> select)
{
try
{
count = Collection.CountDocuments(filter);
var query = Collection.AsQueryable().Where(filter).OrderBy(field, dir);
var data = query.Skip(SkipCount).Take(pageSize).Select(select).ToList();
return data;
}
catch (Exception ex)
{
throw new UserFriendlyException(ex.Message);
}
} #endregion public async Task<bool> AnyAsync(Expression<Func<T, bool>> filter)
{
try
{
long count = await Collection.CountDocumentsAsync(filter);
return count > ;
}
catch (Exception ex)
{
throw new UserFriendlyException(ex.Message);
}
} public bool Any(string collName, Expression<Func<T, bool>> filter)
{
try
{
long count = Collection.CountDocuments(filter);
return count > ;
}
catch (Exception ex)
{
throw ex;
}
} }

5.初始化MongodbHelper

  string dbName = "测试CRUD";
string collectionName ="mongdb";
var InventoryHelper = new MongoDbRepository<Customer>
(new MongoDBConfig { CollectionName = collectionName, DbName = dbName, ConnectionString ="mongodb://localhost");
var list=InventoryHelper.FindList(x=>true);// 得到集合所有的元素

最新文章

  1. C# VLCPlayer视频播放器(附源码)
  2. ASP.NET MVC怎样引用你的model
  3. 让webstorm支持avalon语法自动补全
  4. MyEclipse中无法识别 sun.misc.BASE64Encoder
  5. zk框架window之间传值操作
  6. CodeForces 701A Cards
  7. python 调用系统命令
  8. h5-4 canvas
  9. JS基础DOM篇之二:DOM级别与节点层次?
  10. RedHat7搭建无人值守自动安装Linux操作系统(PXE+Kickstart)
  11. hdu3599 War(最大流)
  12. WEB-INF文件夹的位置和作用
  13. ASP.NET MVC View向Controller提交数据
  14. C# DateDateTimePicker设置属性ShowCheckBox为True
  15. ASP.NET Core 部署IIS及 OFFSET 附近有语法错误解决
  16. mysql 几种日志
  17. 关于TSql
  18. 数据库基础SQL知识面试题二
  19. 修改注册表.exe的文件目录
  20. anaconda3/lib/libcrypto.so.1.0.0: no version information available (required by wget)

热门文章

  1. UVa540 Team Queue(队列queue)
  2. pycharm 如何自动添加头注释,比如时间,作者信息等
  3. Java-DateHandler工具类
  4. node压缩文件
  5. WPF程序发布有关事项
  6. 解压 压缩 C#
  7. CF #366 DIV2 C. Thor 模拟 queue/stack降低复杂度
  8. fhq Treap(无旋Treap)
  9. 总结了零基础学习Java编程语言的几个基础知识要点
  10. python3网络编程