.net core 中使用MongoDB

2023-05-16

https://www.thecodebuzz.com/exception-filters-in-net-core/

https://www.mongodb.com/docs/drivers/csharp/

https://www.mongodb.com/developer/languages/csharp/create-restful-api-dotnet-core-mongodb/

  1. 安装依赖的包
    在这里插入图片描述
  2. 定义服务接口
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MongoDBHelper.Helper
{
    public interface IMongoDB<T> where T : class
    {


        Task InsertOne(T document);


        Task InsertMany(List<T> documents);


        Task<long> BulkInsert(List<T> documents);


        Task<UpdateResult> UpdateOne(string name, string id);


        Task<UpdateResult> UpdateMultiFields(T document, string id);


        Task Inc(string id);


        Task<List<T>> GetAll();


        Task<T> GetOneByID(string id);
    }
}

  1. 定义实体类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;

namespace MongoDBHelper.Model
{
    public class Person
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string? Id { get; set; }
		
		//我们系统里这个字段名称是Age。但是MongoDB存的是age
        [BsonElement("age")]
        [JsonPropertyName("age")]
        public int Age { get; set; }

        [BsonElement("name")]
        [JsonPropertyName("name")]
        public string Name { get; set; }

		//系统以及MongoDB里都是address
        public string address { get; set; }
		//这个字段不会存到MongoDB中
        [BsonIgnore]
        public string IgnoreField { get; set; }
    }
}

  1. 定义helper 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using Microsoft.Extensions.Options;
using MongoDBHelper.Model;
using MongoDB.Bson;

namespace MongoDBHelper.Helper
{
    public class MongoDBTools<T>: IMongoDB<T> where T : Person
    {
        public readonly IMongoCollection<T> mongoCollection;

        public IOptionsSnapshot<Config> _config;
        
        public MongoDBTools(IOptionsSnapshot<Config> config)
        {
            _config = config;
            MongoClient client = new MongoClient(config.Value.connectstring);

            var database = client.GetDatabase(config.Value.database);

            mongoCollection = database.GetCollection<T>(config.Value.collection);
        }

        public Task InsertOne(T document)
        {
            return mongoCollection.InsertOneAsync(document);
        }

        public Task InsertMany(List<T> documents)
        {
            return mongoCollection.InsertManyAsync(documents,new InsertManyOptions() { IsOrdered=false});
        }


        //批量插入,忽略排序
        //默认是不忽略排序的,以这种方式插入数据,假如中间的失败了,则以后的也不再插入
        //取消默认排序后,即使中间又失败的数据,后续数据也会继续插入

        public async Task<long> BulkInsert(List<T> documents)
        {
            try
            {
                List<WriteModel<T>> values = new List<WriteModel<T>>();

                foreach (var item in documents)
                {
                    values.Add(new InsertOneModel<T>(item));
                }
                return mongoCollection.BulkWriteAsync(documents.Select(x => new InsertOneModel<T>(x)).ToList(), new BulkWriteOptions() { IsOrdered = true }).Result.InsertedCount;
            }
            catch (Exception)
            {
                Exception exception = new Exception("批量插入失败");
                throw exception;
            }
            
        }

        public Task<UpdateResult> UpdateOne(string name,string id)
        {
            UpdateDefinition<T> update = Builders<T>.Update.AddToSet<string>("name", name);
            return mongoCollection.UpdateOneAsync(Builders<T>.Filter.Eq("Id",id), update);
        }


        public Task<UpdateResult> UpdateMultiFields(T document,string id)
        {
            UpdateDefinition<T> updateDefinition = Builders<T>.Update.Set(x => x.Name, document.Name).Set(x=>x.Age,document.Age);

            return mongoCollection.UpdateOneAsync(Builders<T>.Filter.Eq("Id", id), updateDefinition);

        }


        public Task Inc(string id)
        {
            FilterDefinition<T> filterDefinition = Builders<T>.Filter.Eq("Id", id);

            UpdateDefinition<T> updateDefinition = Builders<T>.Update.Inc("Age", 1);

            return mongoCollection.UpdateOneAsync(filterDefinition, updateDefinition);
        }


        public async Task<List<T>> GetAll()
        {
            return await mongoCollection.FindSync(new BsonDocument()).ToListAsync();
        }

        public Task<T> GetOneByID(string id)
        {
            return mongoCollection.Find(Builders<T>.Filter.Eq("Id",id)).FirstOrDefaultAsync();
        }
    }
}


  1. 定义controller
using Microsoft.AspNetCore.Mvc;
using MongoDBHelper.Helper;
using MongoDBHelper.Model;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace CoreMongoDB.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MongoDB : ControllerBase
    {
        public readonly IMongoDB<Person> _mongoDBTools;

        public MongoDB(IMongoDB<Person> mongoDBTools)
        {
            _mongoDBTools = mongoDBTools;
        }

        [HttpPost]
        public async Task<bool> InsertOne([FromBody] Person person)
        {
            await _mongoDBTools.InsertOne(person);

            return true;
        }


        [HttpGet]
        public Task<List<Person>> ListAll()
        {
            return _mongoDBTools.GetAll();
        }


        [HttpGet]
        public Task<Person> GetByID([FromQuery] string id)
        {
            return _mongoDBTools.GetOneByID(id);
        }

        [HttpPost]
        public async Task<long> BulkInsert([FromBody] List<Person> persons)
        {
            return await _mongoDBTools.BulkInsert(persons);
        }

        [HttpPut]
        public long UpdateMultiFields([FromBody] Person person,[FromQuery] string id)
        {
            return   _mongoDBTools.UpdateMultiFields(person, id).Result.ModifiedCount;

        }
    }
}

  1. 定义全局异常filter
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace CoreMongoDB.Exception
{
    public class ExceptionHandler : IAsyncExceptionFilter
    {
        public Task OnExceptionAsync(ExceptionContext context)
        {
            string message = context.Exception.Message;
            ObjectResult objectResult = new ObjectResult(new { code = 500, msg = message });

            //Logs your technical exception with stack trace below
            context.Result = objectResult;
            return Task.CompletedTask;
        }
    }
}

  1. 依赖注入
builder.Services.Configure<Config>(
    builder.Configuration.GetSection("MongoDBConfig"));

builder.Services.AddScoped<Config>();


builder.Services.AddScoped(typeof(IMongoDB<>),typeof(MongoDBTools<>));

builder.Services.Configure<MvcOptions>(opt =>
{
    opt.Filters.Add<ExceptionHandler>();
});

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

.net core 中使用MongoDB 的相关文章

  • 只允许在 datagridview 单元格中键入一些字符

    有没有办法只将某些字符添加到 datagridview 单元格中 像 1234567890 据我所知 您可以使用两种方法来实现此目的 第一个 我认为最好的 是使用 CellValidating 事件DataGridView并检查输入的文本是
  • 如何保存具有多个缩进设置的XmlDocument?

    我需要保存一个XmlDocument以适当的缩进归档 Formatting Indented 但有些节点及其子节点必须排在一行 Formatting None 从那时起如何实现这一目标XmlTextWriter接受整个文档的设置 在 Ahm
  • WPF 列表框在鼠标悬停时选择项目

    我正在尝试为列表框创建一种样式 当鼠标放在该项目上时 该样式会将所选项目设置为该项目 有什么提示吗 您可以使用 ListBox 本身影响其所有项目的样式来完成此操作
  • 如何使用 nosql 构建成就和徽章

    我目前有一个使用 mongodb 作为数据库的社交游戏应用程序 我的问题是 如果我想创建一个积分和徽章系统 有哪些建议 成就 徽章的业务逻辑可能会变得非常复杂并且非常临时 因此实时授予徽章似乎效率不高 我想象将跟踪的操作添加到队列中的某处
  • 以编程方式将 Word 文件另存为图片

    我想将Word文档的第一页另存为图片 使用 C 有什么方法可以做到这一点 您可以将 Word 文档打印到 XPS 文档 在 WPF Net 3 5 应用程序中打开它 并使用 WPF 框架的文档和图像功能将第一个内部固定页面对象转换为位图 如
  • docs.microsoft.com 上的 .NET 平台扩展是什么?

    Microsoft Docs 中有一个框架级导航元素 称为 NET 平台扩展 https learn microsoft com en us dotnet api index view dotnet plat ext 2 1 它包含有关最近
  • 索引 getter 中的 IndexOutOfRangeException

    在我的索引属性中 我检查索引是否超出范围 如果是的话 我抛出一个IndexOutOfBoundsException 当我运行代码分析器 在 VS12 中 时 它抱怨 CA1065 意外位置出现意外异常 参考CA1065的描述 仅 Syste
  • SQL 注入在 winform 中有效吗?

    我正在用 C 制作一个 Windows 软件 我读过关于sql injection但我没有发现它适用于我的应用程序 SQL 注入在 winform 中有效吗 如果是的话如何预防 EDIT 我正在使用文本框来读取用户名和密码 通过使用 tex
  • ComponentOne 3D 曲面地图的替代方案 [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我们正在为我们正在进行的一个新项目研究替代控制库 要求之一是以表面图的形式显示数据 如下面的 Comp
  • Visual Studio中设置“目标框架”有什么作用

    在 Visual Studio 中 您可以为项目设置 目标框架 或多或少的常识是 如果将 目标框架 设置为 例如 NET 4 5 2 则应用程序在仅安装了 NET 4 5 1 的计算机上将无法运行 第一个问题 这是真的吗 第二个问题 该设置
  • 如何在 C# 中搜索 Excel 文件

    我正在使用的代码 private void OpenExcelFile Excel Application exlApp new Microsoft Office Interop Excel Application if exlApp nu
  • Kubernetes Pod 中现在几点了?

    假设我有一些 NET Core 代码在 k8s pod 中运行 我要求 DateTime Now 我假设我将从运行 pod 的主机获取日期时间 有没有办法获得在 k8s 集群中一致的日期时间值 容器中的时钟与主机相同 因为它由内核控制 时区
  • log4net 未记录到数据库

    我有一个奇怪的问题 我的 log4net 设置没有将任何数据记录到数据库中 也没有引发任何异常来通知问题 我已经在一个名为 Log4net Config 的单独文件中定义了配置设置 并且 已经在程序集中引用了它 请注意 我通过 nuget
  • 是否有与 SQL Server newsequentialid() 等效的 .NET

    我们使用 GUID 作为主键 您知道默认情况下它是集群的 将新行插入表中时 它将插入表中的随机页 因为 GUID 是随机的 这会对性能产生可衡量的影响 因为数据库始终会分割数据页 碎片 但我使用顺序 GUID 的主要原因是因为我希望将新行插
  • 我可以在 WinRT / Windows 8 Store 应用程序中绑定 DynamicObject

    我有以下代码 public class MyClass DynamicObject INotifyPropertyChanged Dictionary
  • C# 中的 DateTime.Parse 抛出异常

    我不知道为什么抛出异常 这是工作代码 DateTime Parse 1 12 2012 12 00 00 AM 这是抛出异常的一个 DateTime Parse 1 13 2012 12 00 00 AM 抛出的异常是 格式异常 包括此消息
  • .NET 查询字符串值的正则表达式

    我需要从 Url PathAndQuery 中删除任何 id SomeValue 其中 SomeValue 可以是整数或字符串 它后面可能有也可能没有另一个 符号 所以它可能是 somepage aspx cat 22 id SomeId
  • 自定义编译器警告

    在 Net 中使用 ObsoleteAtribute 时 它 会向您发出编译器警告 告诉您该对象 方法 属性已过时 应使用其他内容 我目前正在从事一个需要大量重构前员工代码的项目 我想编写一个自定义属性 可用于标记方法或属性 这些方法或属性
  • 从原始 URL 获取重定向 URL

    我的数据库中有一个表 其中包含一些网站的 URL 我必须打开这些 URL 并验证这些页面上的一些链接 问题是某些 URL 被重定向到其他 URL 对于这样的 URL 我的逻辑是失败的 有什么方法可以传递原始 URL 字符串并获取重定向的 U
  • 是否有将二进制数据打包成 UTF-16 字符串的标准技术?

    在 NET中 我有任意二进制数据存储在byte 例如图像 现在 我需要将该数据存储在string 旧 API 的 注释 字段 有没有标准技术packing将此二进制数据转换为string 我所说的 打包 是指对于任何相当大且随机的数据集 字

随机推荐