Asp.Net Core MongoDB에 대한 예제 코드
말도 안 돼요, 그냥 코드로 가세요;


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


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


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


public class MongoRepository<T> : IRepository<T> where T : IEntity<string>{#region Constructorprotected MongoRepository(IMongoCollection<T> collection) { DbSet = collection; DbContext = collection.Database; }#endregionpublic IEnumerator<T> 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<T> DbSet { get; }public IMongoDatabase DbContext { get; }#endregion#region Findpublic T GetById(string id) {return Get(a => a.Id.Equals(id)).FirstOrDefault(); }public IEnumerable<T> Get(Expression<Func<T, bool>> predicate) {return DbSet.FindSync(predicate).Current; }public async Task<IEnumerable<T>> GetAsync(Expression<Func<T, bool>> 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<T> entities) { DbSet.InsertMany(entities); }public Task InsertAsync(IEnumerable<T> 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<T>.Filter.Eq(e => e.Id, entity.Id),new BsonDocumentUpdateDefinition<T>(doc)); }public Task<UpdateResult> UpdateAsync(T entity, CancellationToken cancellationToken = new CancellationToken()) {var doc = entity.ToBsonDocument();return DbSet.UpdateOneAsync(Builders<T>.Filter.Eq(e => e.Id, entity.Id),new BsonDocumentUpdateDefinition<T>(doc), cancellationToken: cancellationToken); }#endregion#region Deletepublic T Delete(string id) {return DbSet.FindOneAndDelete(a => a.Id.Equals(id)); }public Task<T> DeleteAsync(string id, CancellationToken cancellationToken = new CancellationToken()) {return DbSet.FindOneAndDeleteAsync(a => a.Id.Equals(id), null, cancellationToken); }public Task<DeleteResult> DeleteAsync(Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = new CancellationToken()) {return DbSet.DeleteManyAsync(predicate, cancellationToken); }public DeleteResult Delete(Expression<Func<T, bool>> predicate) {return DbSet.DeleteMany(predicate); }#endregion#region Otherpublic long Count(Expression<Func<T, bool>> predicate) {return DbSet.Count(predicate); }public Task<long> CountAsync(Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = new CancellationToken()) {return DbSet.CountAsync(predicate, null, cancellationToken); }public bool Exists(Expression<Func<T, bool>> predicate) {return Get(predicate).Any(); }#endregion#region Pagepublic IEnumerable<T> Paged(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> sortBy,int pageSize, int pageIndex = 1) {var sort = Builders<T>.Sort.Descending(sortBy);return DbSet.Find(predicate).Sort(sort).Skip(pageSize * pageIndex - 1).Limit(pageSize).ToList(); }public Task<List<T>> PagedAsync(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> sortBy,int pageSize, int pageIndex = 1, CancellationToken cancellationToken = new CancellationToken()) {return Task.Run(() =>{var sort = Builders<T>.Sort.Descending(sortBy);return DbSet.Find(predicate).Sort(sort).Skip(pageSize * pageIndex - 1).Limit(pageSize).ToList(); }, cancellationToken); }#endregion#region Helper/// <summary>/// 获取类型的所有属性信息/// </summary>/// <typeparam name="T"></typeparam>/// <typeparam name="TProperty"></typeparam>/// <param name="select"></param>/// <returns></returns>private PropertyInfo[] GetPropertyInfos<TProperty>(Expression<Func<T, TProperty>> 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<MongoServers> 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<MongoDBSetting> options) {var permissionSystem =MongoCredential.CreateCredential(options.Value.DataBase, options.Value.UserName, options.Value.Password);var services = new List<MongoServerAddress>();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<ErrorLogs> ErrorLog => _db.GetCollection<ErrorLogs>("Error");public IMongoCollection<ErrorLogs> WarningLog => _db.GetCollection<ErrorLogs>("Warning"); }


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


public interface IErrorLogService : IRepository<ErrorLog>{ }public class ErrorLogService : MongoRepository<ErrorLog>, 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,才疏学浅,请大神多多指教
위 내용은 Asp.Net Core MongoDB에 대한 예제 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











.NET 4.0은 다양한 애플리케이션을 만드는 데 사용되며 객체 지향 프로그래밍, 유연성, 강력한 아키텍처, 클라우드 컴퓨팅 통합, 성능 최적화, 광범위한 라이브러리, 보안, 확장성, 데이터 액세스 및 모바일을 포함한 풍부한 기능을 애플리케이션 개발자에게 제공합니다. 개발 지원.

이 기사는 데비안 시스템에서 MongoDB를 구성하여 자동 확장을 달성하는 방법을 소개합니다. 주요 단계에는 MongoDB 복제 세트 및 디스크 공간 모니터링 설정이 포함됩니다. 1. MongoDB 설치 먼저 MongoDB가 데비안 시스템에 설치되어 있는지 확인하십시오. 다음 명령을 사용하여 설치하십시오. sudoaptupdatesudoaptinstall-imongb-org 2. MongoDB Replica 세트 MongoDB Replica 세트 구성은 자동 용량 확장을 달성하기위한 기초 인 고 가용성 및 데이터 중복성을 보장합니다. MongoDB 서비스 시작 : sudosystemctlstartMongodsudosys

이 기사는 데비안 시스템에서 고도로 사용 가능한 MongoDB 데이터베이스를 구축하는 방법에 대해 설명합니다. 우리는 데이터 보안 및 서비스가 계속 운영되도록하는 여러 가지 방법을 모색 할 것입니다. 주요 전략 : ReplicaSet : ReplicaSet : 복제품을 사용하여 데이터 중복성 및 자동 장애 조치를 달성합니다. 마스터 노드가 실패하면 복제 세트는 서비스의 지속적인 가용성을 보장하기 위해 새 마스터 노드를 자동으로 선택합니다. 데이터 백업 및 복구 : MongoDump 명령을 정기적으로 사용하여 데이터베이스를 백업하고 데이터 손실의 위험을 처리하기 위해 효과적인 복구 전략을 공식화합니다. 모니터링 및 경보 : 모니터링 도구 (예 : Prometheus, Grafana) 배포 MongoDB의 실행 상태를 실시간으로 모니터링하고

해시 값으로 저장되기 때문에 MongoDB 비밀번호를 Navicat을 통해 직접 보는 것은 불가능합니다. 분실 된 비밀번호 검색 방법 : 1. 비밀번호 재설정; 2. 구성 파일 확인 (해시 값이 포함될 수 있음); 3. 코드를 점검하십시오 (암호 하드 코드 메일).

CentOS 시스템 하에서 MongoDB 효율적인 백업 전략에 대한 자세한 설명이 기사는 CentOS 시스템에서 MongoDB 백업을 구현하기위한 다양한 전략을 자세히 소개하여 데이터 보안 및 비즈니스 연속성을 보장 할 것입니다. Docker 컨테이너 환경에서 수동 백업, 시간이 정해진 백업, 자동 스크립트 백업 및 백업 메소드를 다루고 백업 파일 관리를위한 모범 사례를 제공합니다. 수동 백업 : MongoDump 명령을 사용하여 Manual 전체 백업을 수행하십시오 (예 : Mongodump-HlocalHost : 27017-U username-P password-d 데이터베이스 이름 -o/백업 디렉토리이 명령은 지정된 데이터베이스의 데이터 및 메타 데이터를 지정된 백업 디렉토리로 내보내게됩니다.

데비안 시스템에서 MongoDB 데이터베이스를 암호화하려면 다음 단계에 따라 필요합니다. 1 단계 : 먼저 MongoDB 설치 먼저 Debian 시스템이 MongoDB가 설치되어 있는지 확인하십시오. 그렇지 않은 경우 설치를위한 공식 MongoDB 문서를 참조하십시오 : https://docs.mongodb.com/manual/tutorial/install-mongodb-ondodb-on-debian/step 2 : 암호화 키 파일 생성 암호화 키를 포함하는 파일을 만듭니다.

Pinetwork는 혁신적인 모바일 뱅킹 플랫폼 인 Pibank를 출시하려고합니다! Pinetwork는 오늘 Pibank라고 불리는 Elmahrosa (Face) Pimisrbank에 대한 주요 업데이트를 발표했습니다. Pibank는 Pinetwork Cryptocurrency 기능을 완벽하게 통합하여 화폐 통화 및 암호 화폐의 원자 교환을 실현합니다 (US Dollar, Indones rupiah, indensian rupiah and with rupiah and and indensian rupiah and rupiah and and Indones rupiah and rupiahh and rupiah and rupiah and rupiah and rupiah and rupiah and rupiah and rupiah cherrenciance) ). Pibank의 매력은 무엇입니까? 알아 보자! Pibank의 주요 기능 : 은행 계좌 및 암호 화폐 자산의 원 스톱 관리. 실시간 거래를 지원하고 생물학을 채택하십시오

MongoDB 및 Relational Database : 심층 비교이 기사는 NOSQL 데이터베이스 MongoDB와 전통적인 관계형 데이터베이스 (예 : MySQL 및 SQLServer)의 차이점을 심층적으로 탐구합니다. 관계형 데이터베이스는 행 및 열의 테이블 구조를 사용하여 데이터를 구성하는 반면 MongoDB는 유연한 문서 지향 모델을 사용하여 최신 응용 프로그램의 요구에 더 잘 어울립니다. 주로 데이터 구조를 차별화합니다. 관계형 데이터베이스는 사전 정의 된 스키마 테이블을 사용하여 데이터를 저장하고 기본 키와 외부 키를 통해 테이블 간의 관계가 설정됩니다. MongoDB는 JSON과 같은 BSON 문서를 사용하여 컬렉션에 저장하며 각 문서 구조는 패턴없는 설계를 달성하기 위해 독립적으로 변경할 수 있습니다. 건축 설계 : 관계형 데이터베이스는 사전 정의 된 고정 스키마가 필요합니다. MongoDB는 지원합니다
