当前位置: 首页 > news >正文

快速上手MongoDB与.NET/C#整合

话不多说,先了解一下MongoDB,在后端服务中选择一个数据库,是由最适合项目应用场景的架构决策所决定的。在做出决策前就需要了解和学习数据库的相关特性,从数据库官网学习了解它的特性是最适合不过的了。

MongoDB官方手册网站:MongoDB是什么? - 数据库手册 - MongoDB Docs

MongoDB .NET/C# 驱动程序手册网站:快速入门 - C#/.NET 驱动程序 v3.4 - MongoDB Docs

1、添加MongoDB.Driver

dotnet add package MongoDB.Driver

2、添加MongoDB配置信息到appsettings.json中

"MongoDBConfig": {"BooksCollectionName": "Book","DatabaseName": "BookStoreDB","ConnectionString": "mongodb://localhost:27017/",
}

3、创建MongoDB配置信息类

public class MongoDBConfig
{public string BookCollectionName { get; set; } = string.Empty;public string DatabaseName { get; set; } = string.Empty;public string ConnectionString { get; set; } = string.Empty;
}

4、创建实体类-Book

public class Book
{[BsonId][BsonRepresentation(BsonType.ObjectId)]public string Id { get; set; } = ObjectId.GenerateNewId().ToString();[BsonElement("Name")]public string BookName { get; set; } = string.Empty;public decimal Price { get; set; }public string Category { get; set; } = string.Empty;public string Author { get; set; } = string.Empty;[BsonDateTimeOptions(Kind = DateTimeKind.Local)]public DateTime CreationTime { get; set; } = DateTime.Now;
}

注:[BsonDateTimeOptions(Kind = DateTimeKind.Local)]必须要添加的,因为MongoDB写入时间是协调世界时(UTC),不加这样注解,查询出来结果会有时区误差。

5、创建自定义MongoDB上下文

public class MongoDBContext
{public IMongoCollection<Book> Books { get; }public MongoDBContext(MongoDBConfig mongodbConfig){if (mongodbConfig != null){if (string.IsNullOrEmpty(mongodbConfig.ConnectionString))throw new ArgumentException("MongoDB connection is not configured");var client = new MongoClient(mongodbConfig.ConnectionString);var database = client.GetDatabase(mongodbConfig.DatabaseName);Books = database.GetCollection<User>(mongodbConfig.BookCollectionName);}else{throw new ArgumentNullException(nameof(mongodbConfig));}}
}

6、创建自定义MongoDB扩展注入服务

public static class MongoDBServiceExtensions
{public static IServiceCollection AddMongoDB(this IServiceCollection services, IConfiguration configuration){services.Configure<MongoDBConfig>(configuration.GetSection("MongoDBConfig"));services.AddSingleton<MongoDBContext>(provider =>{var settings = configuration.GetSection("MongoDBConfig").Get<MongoDBConfig>();return settings == null? throw new InvalidOperationException("MongoDBConfig is not configured properly."): new MongoDBContext(settings);});return services;}
}

注:这里为什么会将MongoDBContext注册为单例服务,因为官方文档推荐单例模式

7、Program.cs文件中注入MongoDB

builder.Services.AddMongoDB(builder.Configuration);

8、使用MongoDB

[ApiController]
[Route("api/[controller]")]public class BookController : ControllerBase
{private readonly ILogger<BookController> _logger;private readonly MongoDBContext _mongodbContext;public BookController(MongoDBContext mongodbContext, ILogger<BookController> logger){_logger = logger;_mongodbContext = mongodbContext;}[HttpGet]public async Task<List<Book>> GetList(){return await _mongodbContext.Books.Find(_ => true).ToListAsync();}[HttpGet("{id:length(24)}")]public async Task<ActionResult<Book>> Get(string id){var book = await _mongodbContext.Books.Find(x => x.Id == id).FirstOrDefaultAsync();if (book is null){return NotFound();}return book;}[HttpPost]public async Task<IActionResult> Post(Book newBook){await _mongodbContext.Books.InsertOneAsync(newBook);return CreatedAtAction(nameof(Get), new { id = newBook.Id }, newBook);}[HttpPut("{id:length(24)}")]public async Task<IActionResult> Update(string id, Book updatedBook){var book = await _mongodbContext.Books.Find(x => x.Id == id).FirstOrDefaultAsync();if (book is null){return NotFound();}updatedBook.Id = book.Id;await _mongodbContext.Books.ReplaceOneAsync(x => x.Id == id, updatedBook); ;return NoContent();}[HttpDelete("{id:length(24)}")]public async Task<IActionResult> Delete(string id){var book = await _mongodbContext.Books.Find(x => x.Id == id).FirstOrDefaultAsync();if (book is null){return NotFound();}await _mongodbContext.Books.DeleteOneAsync(x => x.Id == id);return NoContent();}
}
http://www.lryc.cn/news/584225.html

相关文章:

  • 跨网文件交换?内外网文件交换十大方法构建安全合规的数据传输通道
  • XSS(跨站脚本攻击)
  • 3.9 spring的mybatis数据库数据回弹以及下划线,驼峰转换
  • 【音视频】TS协议解析
  • 在vscode中和obsidian中使用Mermaid
  • SSRF(ctfshow)
  • 生成式人工智能实战 | 自注意力生成对抗网络(Self-Attention Generative Adversarial Network, SAGAN)
  • Java并发编程中的StampedLock详解:原理、实践与性能优化
  • UI前端大数据可视化实战策略:如何设计交互式数据探索界面?
  • Spring AI Alibaba(2)——通过Graph实现工作流
  • 异步I/O库:libuv、libev、libevent与libeio
  • Ubuntu基础(Python虚拟环境和Vue)
  • 输入框过滤选项列表,el-checkbox-group单选
  • 案例分享--福建洋柄水库大桥智慧桥梁安全监测(二)之数字孪生和系统平台
  • Qt开发:QtConcurrent介绍和使用
  • 【网络】Linux 内核优化实战 - net.ipv4.tcp_max_orphans
  • 如何发现Redis中的bigkey?
  • 数据库复合索引设计:为什么等值查询列应该放在范围查询列前面?
  • ip地址可以精确到什么级别?如何获取/更改ip地址
  • 第1讲:C语言常见概念
  • 实训八——路由器与交换机与网线
  • TCP传输控制层协议深入理解
  • 20250710【再来一题快慢指针】Leetcodehot100之141【首个自己一遍pass】今天计划
  • 【算法笔记】6.LeetCode-Hot100-链表专项
  • 数据跨越信任边界及修复方案
  • 通过vue如何利用 Three 绘制 简单3D模型(源码案例)
  • 观成科技:基于自监督学习技术的恶意加密流量检测方案
  • 科技守护银发睡眠健康:七彩喜睡眠监护仪重塑养老新体验
  • 医学+AI!湖北中医药大学信息工程学院与和鲸科技签约101数智领航计划
  • 图片合并pdf