using Entity.MongoDBHelper;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DAL.Interface;
namespace DAL.Implments
{
public partial class MongoDBBaseDAL : IMongoDBBaseDAL
{
//private readonly MongoDataBaseContext _dbContext;
private IMongoClient _client ;
private IMongoDatabase _database ;
public MongoDBBaseDAL(MongoDataBaseContext mongoDataBase)
{
_client = mongoDataBase._client;
_database = mongoDataBase._database;
}
public IMongoDatabase GetDatabase()
{
return _database;
}
public IMongoCollection GetClient(string collName) where T : class, new()
{
return _database.GetCollection(collName);
}
#region +Add 添加一条数据
///
/// 添加一条数据
///
/// 添加的实体
/// mongodb连接信息
///
public int Add(string collName, T t) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
client.InsertOne(t);
return 1;
}
catch(Exception ex)
{
return 0;
}
}
#endregion
#region +AddAsync 异步添加一条数据
///
/// 异步添加一条数据
///
/// 添加的实体
/// mongodb连接信息
///
public async Task AddAsync(string collName, T t) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
await client.InsertOneAsync(t);
return 1;
}
catch
{
return 0;
}
}
#endregion
#region +InsertMany 批量插入
///
/// 批量插入
///
/// mongodb连接信息
/// 实体集合
///
public int InsertMany(string collName, List t) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
client.InsertMany(t);
return 1;
}
catch (Exception ex)
{
return 0;
}
}
#endregion
#region +InsertManyAsync 异步批量插入
///
/// 异步批量插入
///
/// mongodb连接信息
/// 实体集合
///
public async Task InsertManyAsync(string collName, List t) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
await client.InsertManyAsync(t);
return 1;
}
catch
{
return 0;
}
}
#endregion
#region +Update 修改一条数据
///
/// 修改一条数据
///
/// 添加的实体
/// mongodb连接信息
///
public UpdateResult Update(string collName, T t, string id,bool isObjectId=true) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
//修改条件
FilterDefinition filter;
if (isObjectId)
{
filter = Builders.Filter.Eq("_id", new ObjectId(id));
}
else
{
filter = Builders.Filter.Eq("_id", id);
}
//要修改的字段
var list = new List>();
foreach (var item in t.GetType().GetProperties())
{
if (item.Name.ToLower() == "id") continue;
list.Add(Builders.Update.Set(item.Name, item.GetValue(t)));
}
var updatefilter = Builders.Update.Combine(list);
return client.UpdateOne(filter, updatefilter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region +UpdateAsync 异步修改一条数据
///
/// 异步修改一条数据
///
/// 添加的实体
/// mongodb连接信息
///
public async Task UpdateAsync(string collName, T t, string id,bool isObjectId) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
//修改条件
FilterDefinition filter;
if (isObjectId)
{
filter = Builders.Filter.Eq("_id", new ObjectId(id));
}
else
{
filter = Builders.Filter.Eq("_id", id);
}
//要修改的字段
var list = new List>();
foreach (var item in t.GetType().GetProperties())
{
if (item.Name.ToLower() == "id") continue;
list.Add(Builders.Update.Set(item.Name, item.GetValue(t)));
}
var updatefilter = Builders.Update.Combine(list);
return await client.UpdateOneAsync(filter, updatefilter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region +UpdateManay 批量修改数据
///
/// 批量修改数据
///
/// 要修改的字段
/// mongodb连接信息
/// 修改条件
///
public UpdateResult UpdateManay(string collName, Dictionary dic, FilterDefinition filter) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
T t = new T();
//要修改的字段
var list = new List>();
foreach (var item in t.GetType().GetProperties())
{
if (!dic.ContainsKey(item.Name)) continue;
var value = dic[item.Name];
list.Add(Builders.Update.Set(item.Name, value));
}
var updatefilter = Builders.Update.Combine(list);
return client.UpdateMany(filter, updatefilter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region +UpdateManayAsync 异步批量修改数据
///
/// 异步批量修改数据
///
/// 要修改的字段
/// mongodb连接信息
/// 修改条件
///
public async Task UpdateManayAsync(string collName, Dictionary dic, FilterDefinition filter) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
T t = new T();
//要修改的字段
var list = new List>();
foreach (var item in t.GetType().GetProperties())
{
if (!dic.ContainsKey(item.Name)) continue;
var value = dic[item.Name];
list.Add(Builders.Update.Set(item.Name, value));
}
var updatefilter = Builders.Update.Combine(list);
return await client.UpdateManyAsync(filter, updatefilter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Delete 删除一条数据
///
/// 删除一条数据
///
/// mongodb连接信息
/// objectId
///
public DeleteResult Delete(string collName, string id,bool isObjectId=true) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
FilterDefinition filter;
if (isObjectId)
{
filter = Builders.Filter.Eq("_id", new ObjectId(id));
}
else
{
filter = Builders.Filter.Eq("_id", id);
}
return client.DeleteOne(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region DeleteAsync 异步删除一条数据
///
/// 异步删除一条数据
///
/// mongodb连接信息
/// objectId
///
public async Task DeleteAsync(string collName, string id,bool isObjectId=true) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
//修改条件
FilterDefinition filter;
if (isObjectId)
{
filter = Builders.Filter.Eq("_id", new ObjectId(id));
}
else
{
filter = Builders.Filter.Eq("_id", id);
}
return await client.DeleteOneAsync(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region DeleteMany 删除多条数据
///
/// 删除一条数据
///
/// mongodb连接信息
/// 删除的条件
///
public DeleteResult DeleteMany(string collName, FilterDefinition filter) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
return client.DeleteMany(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region DeleteManyAsync 异步删除多条数据
///
/// 异步删除多条数据
///
/// mongodb连接信息
/// 删除的条件
///
public async Task DeleteManyAsync(string collName, FilterDefinition filter) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
return await client.DeleteManyAsync(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Count 根据条件获取总数
///
/// 根据条件获取总数
///
/// mongodb连接信息
/// 条件
///
public long Count(string collName, FilterDefinition filter) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
return client.Count(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region CountAsync 异步根据条件获取总数
///
/// 异步根据条件获取总数
///
/// mongodb连接信息
/// 条件
///
public async Task CountAsync(string collName, FilterDefinition filter) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
return await client.CountAsync(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region FindOne 根据id查询一条数据
///
/// 根据id查询一条数据
///
/// mongodb连接信息
/// objectid
/// 要查询的字段,不写时查询全部
///
public T FindOne(string collName, string id,bool isObjectId=true, string[] field = null) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
FilterDefinition filter;
if (isObjectId)
{
filter = Builders.Filter.Eq("_id", new ObjectId(id));
}
else
{
filter = Builders.Filter.Eq("_id", id);
}
//不指定查询字段
if (field == null || field.Length == 0)
{
return client.Find(filter).FirstOrDefault();
}
//制定查询字段
var fieldList = new List>();
for (int i = 0; i < field.Length; i++)
{
fieldList.Add(Builders.Projection.Include(field[i].ToString()));
}
var projection = Builders.Projection.Combine(fieldList);
fieldList?.Clear();
return client.Find(filter).Project(projection).FirstOrDefault();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region FindOneAsync 异步根据id查询一条数据
///
/// 异步根据id查询一条数据
///
/// mongodb连接信息
/// objectid
///
public async Task FindOneAsync(string collName, string id,bool isObjectId=true, string[] field = null) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
FilterDefinition filter;
if (isObjectId)
{
filter = Builders.Filter.Eq("_id", new ObjectId(id));
}
else
{
filter = Builders.Filter.Eq("_id", id);
}
//不指定查询字段
if (field == null || field.Length == 0)
{
return await client.Find(filter).FirstOrDefaultAsync();
}
//制定查询字段
var fieldList = new List>();
for (int i = 0; i < field.Length; i++)
{
fieldList.Add(Builders.Projection.Include(field[i].ToString()));
}
var projection = Builders.Projection.Combine(fieldList);
fieldList?.Clear();
return await client.Find(filter).Project(projection).FirstOrDefaultAsync();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region FindList 查询集合
///
/// 查询集合
///
/// mongodb连接信息
/// 查询条件
/// 要查询的字段,不写时查询全部
/// 要排序的字段
///
public List FindList(string collName, FilterDefinition filter, string[] field = null, SortDefinition sort = null) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
//不指定查询字段
if (field == null || field.Length == 0)
{
if (sort == null) return client.Find(filter).ToList();
//进行排序
return client.Find(filter).Sort(sort).ToList();
}
//制定查询字段
var fieldList = new List>();
for (int i = 0; i < field.Length; i++)
{
fieldList.Add(Builders.Projection.Include(field[i].ToString()));
}
var projection = Builders.Projection.Combine(fieldList);
fieldList?.Clear();
if (sort == null) return client.Find(filter).Project(projection).ToList();
//排序查询
return client.Find(filter).Sort(sort).Project(projection).ToList();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region FindListAsync 异步查询集合
///
/// 异步查询集合
///
/// mongodb连接信息
/// 查询条件
/// 要查询的字段,不写时查询全部
/// 要排序的字段
///
public async Task> FindListAsync(string collName, FilterDefinition filter, string[] field = null, SortDefinition sort = null) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
//不指定查询字段
if (field == null || field.Length == 0)
{
if (sort == null) return await client.Find(filter).ToListAsync();
return await client.Find(filter).Sort(sort).ToListAsync();
}
//制定查询字段
var fieldList = new List>();
for (int i = 0; i < field.Length; i++)
{
fieldList.Add(Builders.Projection.Include(field[i].ToString()));
}
var projection = Builders.Projection.Combine(fieldList);
fieldList?.Clear();
if (sort == null) return await client.Find(filter).Project(projection).ToListAsync();
//排序查询
return await client.Find(filter).Sort(sort).Project(projection).ToListAsync();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region FindListByPage 分页查询集合
///
/// 分页查询集合
///
/// mongodb连接信息
/// 查询条件
/// 当前页
/// 页容量
/// 总条数
/// 要查询的字段,不写时查询全部
/// 要排序的字段
///
public List FindListByPage(string collName, FilterDefinition filter, int pageIndex, int pageSize, out long count, string[] field = null, SortDefinition sort = null) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
count = client.Count(filter);
//不指定查询字段
if (field == null || field.Length == 0)
{
if (sort == null) return client.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
//进行排序
return client.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
}
//制定查询字段
var fieldList = new List>();
for (int i = 0; i < field.Length; i++)
{
fieldList.Add(Builders.Projection.Include(field[i].ToString()));
}
var projection = Builders.Projection.Combine(fieldList);
fieldList?.Clear();
//不排序
if (sort == null) return client.Find(filter).Project(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
//排序查询
return client.Find(filter).Sort(sort).Project(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region FindListByPageAsync 异步分页查询集合
///
/// 异步分页查询集合
///
/// mongodb连接信息
/// 查询条件
/// 当前页
/// 页容量
/// 要查询的字段,不写时查询全部
/// 要排序的字段
///
public async Task> FindListByPageAsync(string collName, FilterDefinition filter, int pageIndex, int pageSize, string[] field = null, SortDefinition sort = null) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
//不指定查询字段
if (field == null || field.Length == 0)
{
if (sort == null) return await client.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
//进行排序
return await client.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
}
//制定查询字段
var fieldList = new List>();
for (int i = 0; i < field.Length; i++)
{
fieldList.Add(Builders.Projection.Include(field[i].ToString()));
}
var projection = Builders.Projection.Combine(fieldList);
fieldList?.Clear();
//不排序
if (sort == null) return await client.Find(filter).Project(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
//排序查询
return await client.Find(filter).Sort(sort).Project(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
public async Task AnyAsync(string collName, FilterDefinition filter) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
long count =await client.CountAsync(filter);
return count > 0;
}
catch (Exception ex)
{
throw ex;
}
}
public bool Any(string collName, FilterDefinition filter) where T : class, new()
{
try
{
var client = _database.GetCollection(collName);
long count = client.Count(filter);
return count > 0;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
连接类
using MongoDB.Bson;
using MongoDB.Driver;
namespace Entity.MongoDBHelper
{
public class MongoDataBaseContext
{
public IMongoClient _client = null;
public IMongoDatabase _database = null;
public MongoDataBaseContext(MongodbHost host)
{
_client = new MongoClient(host.Connection);
_database = _client.GetDatabase(host.DataBase);
}
}
public class MongodbHost
{
///
/// 连接字符串
///
public string Connection { get; set; }
///
/// 库
///
public string DataBase { get; set; }
///
/// 表
///
public string Table { get; set; }
}
}
调用:
FilterDefinition filter = Builders.Filter.Empty;
filter = filter & Builders.Filter.Eq(a => a.User.UserId, userId.ToString().ToUpper());
long countRecognized = await _mongoDB.CountAsync(MGTable.Approvals, filter);//获取条件下的总数量
//排序
SortDefinition sort = Builders.Sort.Descending(a => a.CreateDate);
if (parameters.Order.ToUpper() == "DESC")
{
sort = Builders.Sort.Descending(c=>c.CreateDate);
}
if (parameters.Order.ToUpper() == "ASC")
{
sort = Builders.Sort.Ascending(c => c.CreateDate);
}
//查询字段
string[] fileds = null;
_mongoDB.FindListByPage(MGTable.Approvals, filter & Builders.Filter.Eq(b => b.ToUser.UserId, a.ItemId.ToString().ToUpper()), page, pageSize,out countAll, fileds, sort);//表名,条件,分页,总数量,字段,排序