废话不说直接上代码;


using MongoDB.Bson.Serialization.Attributes;namespace XL.Core.MongoDB
{public interface IEntity{/// /// 主键/// [BsonId]
TKey Id { get; set; }
}
} 

[BsonIgnoreExtraElements(Inherited = true)]public abstract class Entity : IEntity{/// /// 主键/// [BsonRepresentation(BsonType.ObjectId)]public virtual string Id { get; set; } }


public interface IRepository: IQueryable where T : IEntity {#region Fileds/// /// MongoDB表/// IMongoCollectionDbSet { get; }/// /// MongoDB库/// IMongoDatabase DbContext { get; }#endregion#region Find////// 根据主键获取对象/// /// ///T GetById(TKey id);/// /// 获取对象/// /// ///IEnumerable Get(Expression > predicate);/// /// 获取对象/// /// /// ///Task > GetAsync(Expression > predicate, CancellationToken cancellationToken = default(CancellationToken));#endregion#region Insert/// /// 插入文档/// /// ///T Insert(T entity);/// /// 异步插入文档/// /// /// ///Task InsertAsync(T entity, CancellationToken cancellationToken = default(CancellationToken));/// /// Adds the new entities in the repository./// /// The entities of type T.void Insert(IEnumerableentities);/// /// 插入文档/// /// /// ///Task InsertAsync(IEnumerable entities, CancellationToken cancellationToken = default(CancellationToken));#endregion#region Update/// /// 更新文档/// /// ///UpdateResult Update(T entity);/// /// 异步更新文档/// /// /// ///Task UpdateAsync(T entity, CancellationToken cancellationToken = default(CancellationToken));#endregion#region Delete/// /// 根据主键ID/// /// ///T Delete(TKey id);/// /// 异步根据ID删除文档/// /// /// ///Task DeleteAsync(TKey id, CancellationToken cancellationToken = default(CancellationToken));/// /// 异步删除/// /// /// ///Task DeleteAsync(Expression > predicate, CancellationToken cancellationToken = default(CancellationToken));/// /// 删除/// /// ///DeleteResult Delete(Expression > predicate);#endregion#region Other/// /// 计数/// /// ///long Count(Expression > predicate);/// /// 计数/// /// /// ///Task CountAsync(Expression > predicate, CancellationToken cancellationToken = new CancellationToken());/// /// 是否存在/// /// ///bool Exists(Expression > predicate);#endregion#region Query/// /// 分页/// 注:只适合单属性排序/// /// /// /// /// ///IEnumerable Paged(Expression > predicate, Expression > sortBy,int pageSize, int pageIndex = 1);/// /// /// /// /// /// /// /// ///Task > PagedAsync(Expression
> predicate, Expression > sortBy,int pageSize, int pageIndex = 1, CancellationToken cancellationToken = new CancellationToken());#endregion} public interface IRepository : IRepository where T : IEntity { }


public class MongoRepository: IRepository where T : IEntity {#region Constructorprotected MongoRepository(IMongoCollection collection) { DbSet = collection; DbContext = collection.Database; }#endregionpublic IEnumerator GetEnumerator() {return DbSet.AsQueryable().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() {return GetEnumerator(); }#region 字段public Type ElementType => DbSet.AsQueryable().ElementType;public Expression Expression => DbSet.AsQueryable().Expression;public IQueryProvider Provider => DbSet.AsQueryable().Provider;public IMongoCollection DbSet { get; }public IMongoDatabase DbContext { get; }#endregion#region Findpublic T GetById(string id) {return Get(a => a.Id.Equals(id)).FirstOrDefault(); }public IEnumerable Get(Expression > predicate) {return DbSet.FindSync(predicate).Current; }public async Task > GetAsync(Expression > predicate, CancellationToken cancellationToken = new CancellationToken()) {var task = await DbSet.FindAsync(predicate, null, cancellationToken);return task.Current; }#endregion#region Insertpublic T Insert(T entity) { DbSet.InsertOne(entity);return entity; }public Task InsertAsync(T entity, CancellationToken cancellationToken = new CancellationToken()) {return DbSet.InsertOneAsync(entity, null, cancellationToken); }public void Insert(IEnumerable entities) { DbSet.InsertMany(entities); }public Task InsertAsync(IEnumerable entities, CancellationToken cancellationToken = new CancellationToken()) {return DbSet.InsertManyAsync(entities, null, cancellationToken); }#endregion#region Updatepublic UpdateResult Update(T entity) {var doc = entity.ToBsonDocument();return DbSet.UpdateOne(Builders .Filter.Eq(e => e.Id, entity.Id),new BsonDocumentUpdateDefinition (doc)); }public Task UpdateAsync(T entity, CancellationToken cancellationToken = new CancellationToken()) {var doc = entity.ToBsonDocument();return DbSet.UpdateOneAsync(Builders .Filter.Eq(e => e.Id, entity.Id),new BsonDocumentUpdateDefinition (doc), cancellationToken: cancellationToken); }#endregion#region Deletepublic T Delete(string id) {return DbSet.FindOneAndDelete(a => a.Id.Equals(id)); }public Task DeleteAsync(string id, CancellationToken cancellationToken = new CancellationToken()) {return DbSet.FindOneAndDeleteAsync(a => a.Id.Equals(id), null, cancellationToken); }public Task DeleteAsync(Expression > predicate, CancellationToken cancellationToken = new CancellationToken()) {return DbSet.DeleteManyAsync(predicate, cancellationToken); }public DeleteResult Delete(Expression > predicate) {return DbSet.DeleteMany(predicate); }#endregion#region Otherpublic long Count(Expression > predicate) {return DbSet.Count(predicate); }public Task CountAsync(Expression > predicate, CancellationToken cancellationToken = new CancellationToken()) {return DbSet.CountAsync(predicate, null, cancellationToken); }public bool Exists(Expression > predicate) {return Get(predicate).Any(); }#endregion#region Pagepublic IEnumerable Paged(Expression > predicate, Expression > sortBy,int pageSize, int pageIndex = 1) {var sort = Builders .Sort.Descending(sortBy);return DbSet.Find(predicate).Sort(sort).Skip(pageSize * pageIndex - 1).Limit(pageSize).ToList(); }public Task > PagedAsync(Expression
> predicate, Expression > sortBy,int pageSize, int pageIndex = 1, CancellationToken cancellationToken = new CancellationToken()) {return Task.Run(() =>{var sort = Builders .Sort.Descending(sortBy);return DbSet.Find(predicate).Sort(sort).Skip(pageSize * pageIndex - 1).Limit(pageSize).ToList(); }, cancellationToken); }#endregion#region Helper/// /// 获取类型的所有属性信息/// ////// /// /// private PropertyInfo[] GetPropertyInfos (Expression > select) {var body = select.Body;switch (body.NodeType) {case ExpressionType.Parameter:var parameterExpression = body as ParameterExpression;if (parameterExpression != null) return parameterExpression.Type.GetProperties();break;case ExpressionType.New:var newExpression = body as NewExpression;if (newExpression != null)return newExpression.Members.Select(m => m as PropertyInfo).ToArray();break; }return null; }#endregion}
使用如下:


public class MongoDBSetting
{public string DataBase { get; set; }public string UserName { get; set; }public string Password { get; set; }public List Services { get; set; }
}public class MongoServers
{public string Host { get; set; }public int Port { get; set; } = 27017;
}


public class LogsContext
{private readonly IMongoDatabase _db;public LogsContext(IOptions options)
{var permissionSystem =MongoCredential.CreateCredential(options.Value.DataBase, options.Value.UserName,
options.Value.Password);var services = new List();foreach (var item in options.Value.Services)
{
services.Add(new MongoServerAddress(item.Host, item.Port));
}var settings = new MongoClientSettings
{
Credentials = new[] {permissionSystem},
Servers = services
};var _mongoClient = new MongoClient(settings);
_db = _mongoClient.GetDatabase(options.Value.DataBase);
}public IMongoCollection ErrorLog => _db.GetCollection("Error");public IMongoCollection WarningLog => _db.GetCollection("Warning");
} 

public static IServiceCollection UserMongoLog(this IServiceCollection services,
IConfigurationSection configurationSection)
{
services.Configure(configurationSection);
services.AddSingleton();return services;
} 

public interface IErrorLogService : IRepository{ }public class ErrorLogService : MongoRepository , IErrorLogService {public ErrorLogService(LogsContext dbContext) : base(dbContext.ErrorLog) { } }
最后:


services.UserMongoLog(Configuration.GetSection("Mongo.Log"));

"Mongo.Log": {"DataBase": "PermissionSystem","UserName": "sa","Password": "shtx@123","Services": [
{"Host": "192.168.1.6","Port": "27017" }
]
}刚学洗使用MongoDB,才疏学浅,请大神多多指教










