Mongodb for .Net Core 封装类库
一:引用的mongodb驱动文件版本为 Mongodb.Driver 20.4.3
二:我只是进行了常用方法的封装,如有不当之处,请联系我
创建mongodb的连接
using MongoDB.Bson;
using MongoDB.Driver;
namespace MongodbTest.Comon
{
public static class MongodbClient<T> where T : class
{
#region +MongodbInfoClient 获取mongodb实例
/// <summary>
/// 获取mongodb实例
/// </summary>
/// <param name="host">连接字符串,库,表</param>
/// <returns></returns>
public static IMongoCollection<T> MongodbInfoClient(MongodbHost host)
{
MongoClient client = new MongoClient(host.Connection);
var dataBase = client.GetDatabase(host.DataBase);
return dataBase.GetCollection<T>(host.Table);
}
#endregion
} public class MongodbHost
{
/// <summary>
/// 连接字符串
/// </summary>
public string Connection { get; set; }
/// <summary>
/// 库
/// </summary>
public string DataBase { get; set; }
/// <summary>
/// 表
/// </summary>
public string Table { get; set; } }
}
三:mongodb的增删改查
public static class TMongodbHelper<T> where T : class, new()
{
#region +Add 添加一条数据
/// <summary>
/// 添加一条数据
/// </summary>
/// <param name="t">添加的实体</param>
/// <param name="host">mongodb连接信息</param>
/// <returns></returns>
public static int Add(MongodbHost host, T t)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
client.InsertOne(t);
return ;
}
catch
{
return ;
}
}
#endregion #region +AddAsync 异步添加一条数据
/// <summary>
/// 异步添加一条数据
/// </summary>
/// <param name="t">添加的实体</param>
/// <param name="host">mongodb连接信息</param>
/// <returns></returns>
public static async Task<int> AddAsync(MongodbHost host, T t)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
await client.InsertOneAsync(t);
return ;
}
catch
{
return ;
}
}
#endregion #region +InsertMany 批量插入
/// <summary>
/// 批量插入
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="t">实体集合</param>
/// <returns></returns>
public static int InsertMany(MongodbHost host, List<T> t)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
client.InsertMany(t);
return ;
}
catch (Exception ex)
{
return ;
}
}
#endregion #region +InsertManyAsync 异步批量插入
/// <summary>
/// 异步批量插入
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="t">实体集合</param>
/// <returns></returns>
public static async Task<int> InsertManyAsync(MongodbHost host, List<T> t)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
await client.InsertManyAsync(t);
return ;
}
catch
{
return ;
}
}
#endregion #region +Update 修改一条数据
/// <summary>
/// 修改一条数据
/// </summary>
/// <param name="t">添加的实体</param>
/// <param name="host">mongodb连接信息</param>
/// <returns></returns>
public static UpdateResult Update(MongodbHost host, T t, string id)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
//修改条件
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
//要修改的字段
var list = new List<UpdateDefinition<T>>();
foreach (var item in t.GetType().GetProperties())
{
if (item.Name.ToLower() == "id") continue;
list.Add(Builders<T>.Update.Set(item.Name, item.GetValue(t)));
}
var updatefilter = Builders<T>.Update.Combine(list);
return client.UpdateOne(filter, updatefilter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region +UpdateAsync 异步修改一条数据
/// <summary>
/// 异步修改一条数据
/// </summary>
/// <param name="t">添加的实体</param>
/// <param name="host">mongodb连接信息</param>
/// <returns></returns>
public static async Task<UpdateResult> UpdateAsync(MongodbHost host, T t, string id)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
//修改条件
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
//要修改的字段
var list = new List<UpdateDefinition<T>>();
foreach (var item in t.GetType().GetProperties())
{
if (item.Name.ToLower() == "id") continue;
list.Add(Builders<T>.Update.Set(item.Name, item.GetValue(t)));
}
var updatefilter = Builders<T>.Update.Combine(list);
return await client.UpdateOneAsync(filter, updatefilter);
}
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 static UpdateResult UpdateManay(MongodbHost host, Dictionary<string, string> dic, FilterDefinition<T> filter)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
T t = new T();
//要修改的字段
var list = new List<UpdateDefinition<T>>();
foreach (var item in t.GetType().GetProperties())
{
if (!dic.ContainsKey(item.Name)) continue;
var value = dic[item.Name];
list.Add(Builders<T>.Update.Set(item.Name, value));
}
var updatefilter = Builders<T>.Update.Combine(list);
return client.UpdateMany(filter, updatefilter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region +UpdateManayAsync 异步批量修改数据
/// <summary>
/// 异步批量修改数据
/// </summary>
/// <param name="dic">要修改的字段</param>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">修改条件</param>
/// <returns></returns>
public static async Task<UpdateResult> UpdateManayAsync(MongodbHost host, Dictionary<string, string> dic, FilterDefinition<T> filter)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
T t = new T();
//要修改的字段
var list = new List<UpdateDefinition<T>>();
foreach (var item in t.GetType().GetProperties())
{
if (!dic.ContainsKey(item.Name)) continue;
var value = dic[item.Name];
list.Add(Builders<T>.Update.Set(item.Name, value));
}
var updatefilter = Builders<T>.Update.Combine(list);
return await client.UpdateManyAsync(filter, updatefilter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region Delete 删除一条数据
/// <summary>
/// 删除一条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="id">objectId</param>
/// <returns></returns>
public static DeleteResult Delete(MongodbHost host, string id)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
return client.DeleteOne(filter);
}
catch (Exception ex)
{
throw ex;
} }
#endregion #region DeleteAsync 异步删除一条数据
/// <summary>
/// 异步删除一条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="id">objectId</param>
/// <returns></returns>
public static async Task<DeleteResult> DeleteAsync(MongodbHost host, string id)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
//修改条件
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
return await client.DeleteOneAsync(filter);
}
catch (Exception ex)
{
throw ex;
} }
#endregion #region DeleteMany 删除多条数据
/// <summary>
/// 删除一条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">删除的条件</param>
/// <returns></returns>
public static DeleteResult DeleteMany(MongodbHost host, FilterDefinition<T> filter)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
return client.DeleteMany(filter);
}
catch (Exception ex)
{
throw ex;
} }
#endregion #region DeleteManyAsync 异步删除多条数据
/// <summary>
/// 异步删除多条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">删除的条件</param>
/// <returns></returns>
public static async Task<DeleteResult> DeleteManyAsync(MongodbHost host, FilterDefinition<T> filter)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
return await client.DeleteManyAsync(filter);
}
catch (Exception ex)
{
throw ex;
} }
#endregion #region Count 根据条件获取总数
/// <summary>
/// 根据条件获取总数
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">条件</param>
/// <returns></returns>
public static long Count(MongodbHost host, FilterDefinition<T> filter)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
return client.Count(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region CountAsync 异步根据条件获取总数
/// <summary>
/// 异步根据条件获取总数
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">条件</param>
/// <returns></returns>
public static async Task<long> CountAsync(MongodbHost host, FilterDefinition<T> filter)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
return await client.CountAsync(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 static T FindOne(MongodbHost host, string id, string[] field = null)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
//不指定查询字段
if (field == null || field.Length == )
{
return client.Find(filter).FirstOrDefault<T>();
} //制定查询字段
var fieldList = new List<ProjectionDefinition<T>>();
for (int i = ; i < field.Length; i++)
{
fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
}
var projection = Builders<T>.Projection.Combine(fieldList);
fieldList?.Clear();
return client.Find(filter).Project<T>(projection).FirstOrDefault<T>();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region FindOneAsync 异步根据id查询一条数据
/// <summary>
/// 异步根据id查询一条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="id">objectid</param>
/// <returns></returns>
public static async Task<T> FindOneAsync(MongodbHost host, string id, string[] field = null)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
//不指定查询字段
if (field == null || field.Length == )
{
return await client.Find(filter).FirstOrDefaultAsync();
} //制定查询字段
var fieldList = new List<ProjectionDefinition<T>>();
for (int i = ; i < field.Length; i++)
{
fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
}
var projection = Builders<T>.Projection.Combine(fieldList);
fieldList?.Clear();
return await client.Find(filter).Project<T>(projection).FirstOrDefaultAsync();
}
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 static List<T> FindList(MongodbHost host, FilterDefinition<T> filter, string[] field = null, SortDefinition<T> sort = null)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
//不指定查询字段
if (field == null || field.Length == )
{
if (sort == null) return client.Find(filter).ToList();
//进行排序
return client.Find(filter).Sort(sort).ToList();
} //制定查询字段
var fieldList = new List<ProjectionDefinition<T>>();
for (int i = ; i < field.Length; i++)
{
fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
}
var projection = Builders<T>.Projection.Combine(fieldList);
fieldList?.Clear();
if (sort == null) return client.Find(filter).Project<T>(projection).ToList();
//排序查询
return client.Find(filter).Sort(sort).Project<T>(projection).ToList();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region FindListAsync 异步查询集合
/// <summary>
/// 异步查询集合
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">查询条件</param>
/// <param name="field">要查询的字段,不写时查询全部</param>
/// <param name="sort">要排序的字段</param>
/// <returns></returns>
public static async Task<List<T>> FindListAsync(MongodbHost host, FilterDefinition<T> filter, string[] field = null, SortDefinition<T> sort = null)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
//不指定查询字段
if (field == null || field.Length == )
{
if (sort == null) return await client.Find(filter).ToListAsync();
return await client.Find(filter).Sort(sort).ToListAsync();
} //制定查询字段
var fieldList = new List<ProjectionDefinition<T>>();
for (int i = ; i < field.Length; i++)
{
fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
}
var projection = Builders<T>.Projection.Combine(fieldList);
fieldList?.Clear();
if (sort == null) return await client.Find(filter).Project<T>(projection).ToListAsync();
//排序查询
return await client.Find(filter).Sort(sort).Project<T>(projection).ToListAsync();
}
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 static List<T> FindListByPage(MongodbHost host, FilterDefinition<T> filter, int pageIndex, int pageSize, out long count, string[] field = null, SortDefinition<T> sort = null)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
count = client.Count(filter);
//不指定查询字段
if (field == null || field.Length == )
{
if (sort == null) return client.Find(filter).Skip((pageIndex - ) * pageSize).Limit(pageSize).ToList();
//进行排序
return client.Find(filter).Sort(sort).Skip((pageIndex - ) * pageSize).Limit(pageSize).ToList();
} //制定查询字段
var fieldList = new List<ProjectionDefinition<T>>();
for (int i = ; i < field.Length; i++)
{
fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
}
var projection = Builders<T>.Projection.Combine(fieldList);
fieldList?.Clear(); //不排序
if (sort == null) return client.Find(filter).Project<T>(projection).Skip((pageIndex - ) * pageSize).Limit(pageSize).ToList(); //排序查询
return client.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - ) * pageSize).Limit(pageSize).ToList(); }
catch (Exception ex)
{
throw ex;
}
}
#endregion #region FindListByPageAsync 异步分页查询集合
/// <summary>
/// 异步分页查询集合
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">查询条件</param>
/// <param name="pageIndex">当前页</param>
/// <param name="pageSize">页容量</param>
/// <param name="field">要查询的字段,不写时查询全部</param>
/// <param name="sort">要排序的字段</param>
/// <returns></returns>
public static async Task<List<T>> FindListByPageAsync(MongodbHost host, FilterDefinition<T> filter, int pageIndex, int pageSize, string[] field = null, SortDefinition<T> sort = null)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
//不指定查询字段
if (field == null || field.Length == )
{
if (sort == null) return await client.Find(filter).Skip((pageIndex - ) * pageSize).Limit(pageSize).ToListAsync();
//进行排序
return await client.Find(filter).Sort(sort).Skip((pageIndex - ) * pageSize).Limit(pageSize).ToListAsync();
} //制定查询字段
var fieldList = new List<ProjectionDefinition<T>>();
for (int i = ; i < field.Length; i++)
{
fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
}
var projection = Builders<T>.Projection.Combine(fieldList);
fieldList?.Clear(); //不排序
if (sort == null) return await client.Find(filter).Project<T>(projection).Skip((pageIndex - ) * pageSize).Limit(pageSize).ToListAsync(); //排序查询
return await client.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - ) * pageSize).Limit(pageSize).ToListAsync(); }
catch (Exception ex)
{
throw ex;
}
}
#endregion }
三:调用栗子
//1.批量修改,修改的条件
var time = DateTime.Now;
var list = new List<FilterDefinition<PhoneEntity>>();
list.Add(Builders<PhoneEntity>.Filter.Lt("AddTime", time.AddDays()));
list.Add(Builders<PhoneEntity>.Filter.Gt("AddTime", time));
var filter = Builders<PhoneEntity>.Filter.And(list); //2.要修改的字段内容
var dic = new Dictionary<string, string>();
dic.Add("UseAge", "");
dic.Add("Name", "朝阳");
//3.批量修改
var kk = TMongodbHelper<PhoneEntity>.UpdateManay(host, dic, filter);
//根据条件查询集合
var time = DateTime.Now;
var list = new List<FilterDefinition<PhoneEntity>>();
list.Add(Builders<PhoneEntity>.Filter.Lt("AddTime", time.AddDays()));
list.Add(Builders<PhoneEntity>.Filter.Gt("AddTime", time));
var filter = Builders<PhoneEntity>.Filter.And(list);
//2.查询字段
var field = new[] { "Name", "Price", "AddTime" };
//3.排序字段
var sort = Builders<PhoneEntity>.Sort.Descending("AddTime");
var res = TMongodbHelper<PhoneEntity>.FindList(host, filter, field, sort);
//分页查询,查询条件
var time = DateTime.Now;
var list = new List<FilterDefinition<PhoneEntity>>();
list.Add(Builders<PhoneEntity>.Filter.Lt("AddTime", time.AddDays()));
list.Add(Builders<PhoneEntity>.Filter.Gt("AddTime", time));
var filter = Builders<PhoneEntity>.Filter.And(list);
long count = ;
//排序条件
var sort = Builders<PhoneEntity>.Sort.Descending("AddTime");
var res = TMongodbHelper<PhoneEntity>.FindListByPage(host, filter, , , out count, null, sort);
四,缺少sdk文件时,请自行安装
参考文章:http://www.cnblogs.com/yaozhenfa/p/4574898.html
Mongodb for .Net Core 封装类库的更多相关文章
- 适用于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通用)>,现在重新整理一 ...
- Echarts 的 Java 封装类库 转自 https://my.oschina.net/flags/blog/316920
转自: https://my.oschina.net/flags/blog/316920 Echarts 的 Java 封装类库:http://www.oschina.net/p/echarts-ja ...
- Asp.net Core 和类库读取配置文件信息
Asp.net Core 和类库读取配置文件信息 看干货请移步至.net core 读取配置文件公共类 首先开一个脑洞,Asp.net core 被使用这么长时间了,但是关于配置文件(json)的读取 ...
- MongoDB via Dotnet Core数据映射详解
用好数据映射,MongoDB via Dotnet Core开发变会成一件超级快乐的事. 一.前言 MongoDB这几年已经成为NoSQL的头部数据库. 由于MongoDB free schema ...
- RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库
前言 RxHttp是基于RxJava2+Retrofit 2.9.0+OkHttp 4.9.0实现的轻量级,完美兼容MVVM架构的网络请求封装类库,小巧精致,简单易用,轻轻松松搞定网络请求. GitH ...
- ASP.NET Core实现类库项目读取配置文件
前言 之前继续在学习多线程方面的知识,忽然这两天看到博问中有个园友问到如何在.net core类库中读取配置文件,当时一下蒙了,这个提的多好,我居然不知道,于是这两天了解了相关内容才有此篇博客的出现, ...
- 基础拾遗----RabbitMQ(含封装类库源码)
基础拾遗 基础拾遗------特性详解 基础拾遗------webservice详解 基础拾遗------redis详解 基础拾遗------反射详解 基础拾遗------委托详解 基础拾遗----- ...
- Mongodb for .Net Core 驱动的应用
一:我在做.net core 应用mongodb的sdk时,查阅了不少资料,故记录下来,以方便查阅.mongodb类库的版本 mongodb driver 2.4.3,一下方法均来自此版本文件 先看看 ...
- .NET Core在类库中读取配置文件appsettings.json
在.NET Framework框架时代我们的应用配置内容一般都是写在Web.config或者App.config文件中,读取这两个配置文件只需要引用System.Configuration程序集,分别 ...
随机推荐
- Python笔记 【无序】 【一】
----------- r'原始数据' 为了输入[c:\n\d\r\] 代码: ...
- 【转】Python之向日志输出中添加上下文信息
[转]Python之向日志输出中添加上下文信息 除了传递给日志记录函数的参数(如msg)外,有时候我们还想在日志输出中包含一些额外的上下文信息.比如,在一个网络应用中,可能希望在日志中记录客户端的特定 ...
- MySQL中binlog参数:binlog_rows_query_log_events-记录具体的SQL【转】
在使用RBR也就是行格式的时候,去解析binlog,需要逆向才能分析出对应的原始SQL是什么,而且,里面对应的是每一条具体行变更的内容.当然,你可以开启general log,但如果我们需要的只是记录 ...
- jquery获取、设置、删除cookie
获取cookie: function getCookie(cname) { var name = cname + "="; var ca = document.cookie.spl ...
- web-font 个人学习小总结
个人觉得 web-font 分为两种: 第一种就是真正文本字体,客户端没有安装的字体通过远程加载字体来实现特殊字体提高用户体验: icodon.com : http://icodon.com/goo ...
- 关于iwinfo的调试
在调试 主动扫描时,调用命令 “iwinfo wlan0 scan”时, 在iwinfo中添加的调试语句没有打印和记录到log中去. 后查看iwinfo的makefile发现,在生成iwinfo程序 ...
- ES--05
第四十一讲!分词器内部组成 内置分词器 课程大纲 1.什么是分词器 切分词语,normalization(提升recall召回率) 给你一段句子,然后将这段句子拆分成一个一个的单个的单词,同时对每个单 ...
- ansible配合shell脚本批量编译安装python3.6.6
[root@node1:/etc]# tree /etc/ansible/ /etc/ansible/ ├── ansible.cfg ├── hosts ├── python.yml └── rol ...
- 【原创】大数据基础之Kerberos(1)简介、安装、使用
kerberos5-1.17 官方:https://kerberos.org/ 一 简介 The Kerberos protocol is designed to provide reliable a ...
- sql 迈安
SELECT b.* FROM dbo.[耕地肥料_01土壤肥料机构建设基本情况]as b ,bs_org where--县(b.任务id in((select bs_task.id--,bs_org ...