public class MongoDBProvider where T : class{privateIMongoDatabase _db;public string CollectionName { get; set; }private static ConcurrentDictionary dic = new ConcurrentDictionary();private static ConcurrentDictionary diccollection = new ConcurrentDictionary();///
///获取Mongodb要链接的 DatabaseName///
///
///
public string GetDatabaseName(stringdataBaseName)
{if (!string.IsNullOrEmpty(dataBaseName))
{returndataBaseName;
}else{return dic.GetOrAdd(typeof(T).Name, p =>{var attribute = typeof(T).GetAttribute();if (attribute != null && !string.IsNullOrEmpty(attribute.DatabaseName))
{returnattribute.DatabaseName;
}return "";
});
}
}///
///实例化MongoDB提供者///
/// 要连接的字符串标识
/// 要连接的mongodb databasename
public MongoDBProvider(string connectionName, string dataBaseName = null,string collectionName=null)
{
Assert.NotNull(connectionName, nameof(connectionName));
CollectionName=collectionName;var connectionString = dic.GetOrAdd(connectionName, p =>{var configuration = IocManager.ServiceProvider?.GetRequiredService();return configuration[$"ConnectionStrings:{connectionName}"];
});//获取Mongodb要链接的 DatabaseName
dataBaseName =GetDatabaseName(dataBaseName);string concatkey = string.Concat(connectionName, dataBaseName, collectionName);var connectionManager = newMongoDBConnectionManager();if (!connectionManager.Exists(concatkey))
{
MongoUrl mongoUrl= newMongoUrl(connectionString);
MongoClientSettings settings=MongoClientSettings.FromUrl(mongoUrl);
MongoClient client= newMongoClient(settings);if (string.IsNullOrEmpty(dataBaseName))
{
dataBaseName=mongoUrl.DatabaseName;
}
_db=client.GetDatabase(dataBaseName);
connectionManager.Add(concatkey, _db);
}
_db=connectionManager.GetConnection(concatkey);
}///
///获取一个Mongodb 链接///
///
public IMongoCollectionGetCollection()
{if (!string.IsNullOrEmpty(CollectionName))
{return _db.GetCollection(CollectionName);
}else{var collectionName = diccollection.GetOrAdd(typeof(T).Name, p =>{var attribute = typeof(T).GetAttribute();if (attribute != null && !string.IsNullOrEmpty(attribute.CollectionName))
{returnattribute.CollectionName;
}return typeof(T).Name;
});return _db.GetCollection(collectionName);
}
}///
///获取一个Mongodb 链接///
///
public IMongoCollectionGetBsonDocumentCollection()
{if (!string.IsNullOrEmpty(CollectionName))
{return _db.GetCollection(CollectionName);
}else{var collectionName = diccollection.GetOrAdd(typeof(T).Name, p =>{var attribute = typeof(T).GetAttribute();if (attribute != null && !string.IsNullOrEmpty(attribute.CollectionName))
{returnattribute.CollectionName;
}return typeof(T).Name;
});return _db.GetCollection(collectionName);
}
}
public voidAdd(T entity)
{
GetCollection().InsertOne(entity);
}public voidAdd(BsonDocument entity)
{
GetBsonDocumentCollection().InsertOne(entity);
}public void AddList(Listentities)
{
GetCollection().InsertMany(entities);
}public void AddList(Listentities)
{
GetBsonDocumentCollection().InsertMany(entities);
}public bool DeleteById(params object[] entityIds)
{
Dictionary dicts = new Dictionary();for (int i = 0; i < entityIds.Length; i++)
{
dicts.Add("_id",newObjectId(entityIds[i].ToString()));
}var result = GetCollection().DeleteOne(newBsonDocument(dicts));return result != null && result.DeletedCount > 0;
}///
///根据指定对象的ID,从数据库中删除指定指定的对象///
/// 对象的ID集合
/// 执行成功返回true,否则为false。
public bool DeleteBatch(ListidList)
{if (idList == null || idList.Count == 0)
{throw newArgumentException();
}var newidList = idList.Select(p => { return newObjectId(p); });var builder = Builders.Filter;var filter = builder.AnyIn("_id", newBsonArray(newidList));var result =GetBsonDocumentCollection().DeleteMany(filter);return result != null && result.DeletedCount > 0;
}public bool DeleteByQuery(Expression>condition)
{var result =GetCollection().DeleteMany(condition);return result != null && result.DeletedCount > 0;
}public bool DeleteByQuery(FilterDefinitionquery)
{var result =GetBsonDocumentCollection().DeleteMany(query);return result != null && result.DeletedCount > 0;
}public boolSave(T entity)
{
Dictionary dicts = new Dictionary();
Listkeys;if (PropertyInfoHelper.TryGetPrimaryKeys(entity, outkeys))
{for (int i = 0; i < keys.Count; i++)
{
dicts.Add("_id", newObjectId(keys[i].Value.ToString()));
}var update = GetBsonDocumentCollection().ReplaceOne(newBsonDocument(dicts), entity.ToBsonDocument());return (update != null && update.ModifiedCount > 0);
}return false;
}public bool ReplaceOne(BsonDocument t, stringid)
{if (t == null)
{throw newArgumentException();
}if (string.IsNullOrEmpty(id))
{throw new ArgumentException("传入的对象id为空", id);
}bool result = false;var doc = new BsonDocument { { "_id", newObjectId(id) } };//使用 IsUpsert = true ,如果没有记录则写入
var update =GetBsonDocumentCollection().ReplaceOne(doc, t);
result= update != null && update.ModifiedCount > 0;returnresult;
}public bool UpdateOne(FilterDefinition filter, UpdateDefinitionupdate)
{var upresult =GetCollection().UpdateOne(filter, update);return upresult != null && upresult.ModifiedCount > 0;
}//public bool UpdateOneBson(FilterDefinition filter, UpdateDefinition update)//{//var upresult = GetBsonDocumentCollection().UpdateOne(filter, update);//return upresult != null && upresult.ModifiedCount > 0;//}
public bool UpdateMany(FilterDefinition filter, UpdateDefinitionupdate)
{var upresult =GetCollection().UpdateMany(filter, update);return upresult != null && upresult.ModifiedCount > 0;
}public T GetById(params object[] entityIds)
{
Dictionary dicts = new Dictionary();for (int i = 0; i < entityIds.Length; i++)
{
dicts.Add("_id", newObjectId(entityIds[i].ToString()));
}return GetCollection().Find(newBsonDocument(dicts)).FirstOrDefault();
}public BsonDocument GetBsonDocumentById(params object[] entityIds)
{
Dictionary dicts = new Dictionary();for (int i = 0; i < entityIds.Length; i++)
{
dicts.Add("_id", newObjectId(entityIds[i].ToString()));
}return GetBsonDocumentCollection().Find(newBsonDocument(dicts)).FirstOrDefault();
}///
///通过表达式数查询///
///
///
public T GetItemByQuery(Expression>condition)
{returnGetCollection().Find(condition).FirstOrDefault();
}///
///通过///
///
///
public BsonDocument GetItemByQuery(FilterDefinitionfilter)
{returnGetBsonDocumentCollection().Find(filter).FirstOrDefault();
}public int GetCountByQuery(Expression>condition)
{return (int)GetCollection().CountDocuments(condition);
}public int GetCountByQuery(FilterDefinitionfilter)
{return (int)GetBsonDocumentCollection().CountDocuments(filter);
}public List GetListByQuery(Expression>condition)
{returnGetCollection().Find(condition).ToList();
}public List GetListByQuery(Expression> condition, Expression> field, boolisDesc)
{if(isDesc)
{returnGetCollection().Find(condition).SortByDescending(field).ToList();
}else{returnGetCollection().Find(condition).SortBy(field).ToList();
}
}public List GetListByQuery(FilterDefinitionfilter)
{returnGetBsonDocumentCollection().Find(filter).ToList();
}public List GetListByQuery(FilterDefinition filter, string orderBy, boolisDesc)
{var queryable =GetBsonDocumentCollection().Find(filter);var sort = isDesc ? Builders.Sort.Descending(orderBy) : Builders.Sort.Ascending(orderBy);returnqueryable.Sort(sort).ToList();
}public virtual ListGetAllData()
{returnGetBsonDocumentCollection().AsQueryable().ToList();
}public virtual ListGetAllListData()
{returnGetCollection().AsQueryable().ToList();
}public bool IsExists(Expression>condition)
{return GetCollection().Find(condition).FirstOrDefault() != null;
}public bool IsExists(FilterDefinitionfilter)
{return GetBsonDocumentCollection().Find(filter).FirstOrDefault() != null;
}public List GetTopNByQuery(Expression> condition, int number, string orderBy, boolisDesc)
{if(isDesc)
{return GetCollection().Find(condition).SortByDescending(p =>orderBy).Limit(number).ToList();
}else{return GetCollection().Find(condition).SortBy(p =>orderBy).Limit(number).ToList();
}
}public List GetTopNByQuery(FilterDefinition filter, int number, string orderBy, boolisDesc)
{if(isDesc)
{return GetBsonDocumentCollection().Find(filter).SortByDescending(p =>orderBy).Limit(number).ToList();
}else{return GetBsonDocumentCollection().Find(filter).SortBy(p =>orderBy).Limit(number).ToList();
}
}public List GetPagedList(int offset, int limit, Expression> condition, Expression> field, bool isDesc, out inttotal)
{
total= (int)GetCollection().Count(condition);
List list = new List();if(isDesc)
{
list=GetCollection().Find(condition).SortByDescending(field).Skip(offset).Limit(limit).ToList();
}else{
list=GetCollection().Find(condition).SortBy(field).Skip(offset).Limit(limit).ToList();
}returnlist;
}public List GetPagedList(int offset, int limit, FilterDefinition filter, string orderBy, bool isDesc, out inttotal)
{
total= (int)GetBsonDocumentCollection().CountDocuments(filter);var queryable =GetBsonDocumentCollection().Find(filter);var sort = isDesc ? Builders.Sort.Descending(orderBy) : Builders.Sort.Ascending(orderBy);returnqueryable.Sort(sort).Skip(offset).Limit(limit).ToList();//List list = new List();//if (isDesc)//{//list = GetBsonDocumentCollection().Find(filter).SortByDescending(p => orderBy).Skip(offset).Limit(limit).ToList();//}//else//{//list = GetBsonDocumentCollection().Find(filter).SortBy(p => orderBy).Skip(offset).Limit(limit).ToList();//}//return list;
}public List GetAggregateData(PipelineDefinitionpipeLine)
{return GetCollection().Aggregate(pipeLine).ToList();
}public List GetAggregateData(PipelineDefinitionpipeLine)
{return GetBsonDocumentCollection().Aggregate(pipeLine).ToList();
}}