Example code about Asp.Net Core MongoDB
Don’t talk nonsense and go straight to the code;


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}
Use as follows:


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) { } }
Finally:


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


"Mongo.Log": {"DataBase": "PermissionSystem","UserName": "sa","Password": "shtx@123","Services": [ {"Host": "192.168.1.6","Port": "27017" } ] }
刚学洗使用MongoDB,才疏学浅,请大神多多指教
The above is the detailed content of Example code about Asp.Net Core MongoDB. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

.NET 4.0 is used to create a variety of applications and it provides application developers with rich features including: object-oriented programming, flexibility, powerful architecture, cloud computing integration, performance optimization, extensive libraries, security, Scalability, data access, and mobile development support.

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

PiNetwork is about to launch PiBank, a revolutionary mobile banking platform! PiNetwork today released a major update on Elmahrosa (Face) PIMISRBank, referred to as PiBank, which perfectly integrates traditional banking services with PiNetwork cryptocurrency functions to realize the atomic exchange of fiat currencies and cryptocurrencies (supports the swap between fiat currencies such as the US dollar, euro, and Indonesian rupiah with cryptocurrencies such as PiCoin, USDT, and USDC). What is the charm of PiBank? Let's find out! PiBank's main functions: One-stop management of bank accounts and cryptocurrency assets. Support real-time transactions and adopt biospecies

MongoDB and relational database: In-depth comparison This article will explore in-depth the differences between NoSQL database MongoDB and traditional relational databases (such as MySQL and SQLServer). Relational databases use table structures of rows and columns to organize data, while MongoDB uses flexible document-oriented models to better suit the needs of modern applications. Mainly differentiates data structures: Relational databases use predefined schema tables to store data, and relationships between tables are established through primary keys and foreign keys; MongoDB uses JSON-like BSON documents to store them in a collection, and each document structure can be independently changed to achieve pattern-free design. Architectural design: Relational databases need to pre-defined fixed schema; MongoDB supports
