一.背景

公司项目中在做数据存储时使用到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);// 得到集合所有的元素

【经验分享】Mongodb操作类实现CRUD的更多相关文章

  1. mongodb 操作类

    在使用这个类之前,建议先自己去写,把方法都了解了再用,这样你就可以在适当的时候修个此类,另外请自己构建PagerInfo using System; using System.Collections. ...

  2. [经验分享]C# 操作Windows系统计划任务

    背景:我做了一个事情是要自己提前创建好很多要定时执行的任务,在我不在的时候自动执行这些程序,以保证我的工作能无人值守,那么我就需要建立系统计划任务来帮我完成这件事情,当然用脑子想想如何实现,很简单,每 ...

  3. 适用于app.config与web.config的ConfigUtil读写工具类 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类) 基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

    适用于app.config与web.config的ConfigUtil读写工具类   之前文章:<两种读写配置文件的方案(app.config与web.config通用)>,现在重新整理一 ...

  4. 基于MVC4+EasyUI的Web开发框架形成之旅--基类控制器CRUD的操作

    在上一篇随笔中,我对Web开发框架的总体界面进行了介绍,其中并提到了我的<Web开发框架>的控制器的设计关系,Web开发框架沿用了我的<Winform开发框架>的很多架构设计思 ...

  5. 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)

    近期工作中有使用到 MongoDb作为日志持久化对象,需要实现对MongoDb的增.删.改.查,但由于MongoDb的版本比较新,是2.4以上版本的,网上已有的一些MongoDb Helper类都是基 ...

  6. 基于MVC4+EasyUI的Web开发框架形成之旅(6)--基类控制器CRUD的操作

    在上一篇随笔中,我对Web开发框架的总体界面进行了介绍,其中并提到了我的<Web开发框架>的控制器的设计关系,Web开发框架沿用了我的<Winform开发框架>的很多架构设计思 ...

  7. 对实体类的CRUD操作

    --------------------siwuxie095 对实体类的 CRUD 操作 1.创建数据库和表 (1)创建一个 MySQL 连接:mybatis_conn (2)创建一个数据库:myba ...

  8. 【求建议】毕业之声——信院IT类毕业学子经验分享交流会

    一:缘由 在和非常多学子交流,及上课的经历中,发现一个非常普遍的现象:部分大一学生即失去了对学习.对专业的兴趣.有人在迷茫之后奋起直追.从而珍惜利用不多的大学时光努力提高自己.有人在迷茫中沉沦,沉迷于 ...

  9. (转)基于MVC4+EasyUI的Web开发框架形成之旅--基类控制器CRUD的操作

    http://www.cnblogs.com/wuhuacong/p/3352016.html 在上一篇随笔中,我对Web开发框架的总体界面进行了介绍,其中并提到了我的<Web开发框架>的 ...

随机推荐

  1. 查看 SharePoint Server 中的所有网站集

    网站集是具有同一所有者并共享管理设置(例如权限和配额)的一组网站.网站集是在 Web 应用程序中创建的.创建网站集时,将自动在网站集中创建一个首要网站.然后,可以在首要网站下创建一个或多个子网站.首要 ...

  2. JAVA面试/笔试经典题

    1.short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1;有什么错? 对于short s1 = 1; s1 = s1 + 1; 由于s1+1运算时 ...

  3. LeetCode 01 两数之和

    链接:https://leetcode-cn.com/problems/two-sum 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们 ...

  4. tensorflow2.0编程规范

    背景 tensorflow2.0 相比于1.0 有很大变化,1.0版本的placeholder,Session都没有了,2.0版本强推使用keras.keras是一个比较高层的api,确实挺好用的,一 ...

  5. Mybatis 解决问题的记录与博客

    问题:mybatis 空值映射的问题Mybatis在使用resultMap来映射查询结果中的列,如果查询结果中包含空值的列(不是null),则Mybatis在映射的时候,不会映射这个字段 https: ...

  6. 多个Promise执行顺序

    app.isLogin() // 判断是否登录后 .then(res=>{ this.setData({ login: true }, res2=>{ // 清空临时积分 return a ...

  7. Navicat for MySQL 使用

    库创建标准 表查看sql样式

  8. 灰度图像--图像分割 Scharr算子

    学习DIP第46天 转载请标明本文出处:http://blog.csdn.net/tonyshengtan ,出于尊重文章作者的劳动,转载请标明出处!文章代码已托管,欢迎共同开发: https://g ...

  9. 顺序表应用2:多余元素删除之建表算法(SDUT 3325)

    题解: 每次询问一遍,如果已经存在就不用插入表中了. #include <stdio.h> #include <stdlib.h> #include <string.h& ...

  10. linux命令---vi编辑器快速定位行数

    linux命令—vi编辑器快速定位行数.删除当前行.和删除当前行后面的全部内容 1.vi 编辑器如何快速定位到第N行 命令方式下 :n http://bbs.chinaunix.net/thread- ...