一, 前言及 MongoDB 的介绍
最近在整合自己的框架, 顺便把 MongoDBD 的最简单 CRUD 重构一下作为组件化集成到 ASP.NET core 项目中, 当然此篇文章中没有讲解 MongoDB 的集群部署, 等有机会分享一下.
首先, 我们在 MongoDB 的官方文档中看到, MongoDB 的 2.4 以上的 For .Net 的驱动是支持. Net Core 2.0 的.
针对 MongoDB, 我想大家应该不陌生, 没有用过也有听过.
1,MongoDB 是什么?
MongoDB 是一个基于分布式文件存储的数据库, 为 web 应用提供可扩展的高性能数据存储解决方案, 介于关系型数据库和非关系型数据库的产品, 是非关系型数据库中功能最丰富的. 针对于数据处理是一把利器.
2, 什么是关系型数据库和非关系型数据库?
关系型数据库: 在我们所用过的 sqlserver,MySQL 等, 这些都是关系型数据库, 并且关系型数据库是遵循 ACID 原则的, 严格的一致性.
非关系型数据库: 也叫作 NoSQL, 用与超大规模数据的存储, 这些类型的数据存储不需要固定的模式, 无需多余的操作就可以横向扩展.
- 3,RDBMS VS NoSQL
- RDBMS:
高度组织结构化数据
结构化查询语言
数据和关系都存储在单独的表中
严格一致性
基础事务
NoSQL:
没有声明性查询语言
键 - 值对存储, 列存储, 文档存储等
最终一致性
非结构化和不可预知数据
CAP 定理, 高可用, 高性能, 高扩展
我相信讲到这里, 眼尖的同学应该有注意到 CAP 定理和最终一致性, 肯定会联想到 分布式系统, 在这里给你大大的一个赞. 在分布式系统中可以完美的结合 nosql, 提高我们的性能.
4, 介绍一下 RDBMS 与 MongoDB 的一些概念, 有助于帮助大家理解
翻译一下, 即如下:
二, ASP.NET core 集成 MongoDB
1, 为了演示方便我下载了 Windows 版本的 MongoDB server
大家可以自行去官网下载, 然后针对于可视化界面, 我采用了 Robo 3T 这个工具. 很简洁美观的可视化工具. 推荐大家使用.
安装结束后会在 Windows 服务中看到 MongoDB server
然后我们打开一下 Robo 3T, 连接我们的 MongoDB.
2, 开始在项目中配置一下我们的 MongoDB 吧
第一步: 我新建一个 Core2.0 类库
引入了 "MongoDB.Driver" 这个 nuget 包.
然后扩展了 Startup.cs 中的 Services 的扩展方法
- // 扩展方法 public static class ServiceCollectionExtensions
- {
- public static void AddMongoDB(this IServiceCollection services, IConfiguration configuration)
- {
- services.Configure<Settings>(options =>
- {
- options.ConnectionString = configuration.GetSection("MongoConnection:ConnectionString").Value;
- options.Database = configuration.GetSection("MongoConnection:Database").Value;
- });
- }
- }
第二步: 重构封装了 MongoDB 的 CRUD 类, 此处大家可以自行封装, 只展示了查找和新增.
- public class MongoDBBase
- {
- private readonly IMongoDatabase _database = null;
- public MongoDBBase(string connectionString, string databaseName)
- {
- var client = new MongoClient(connectionString);
- if (client != null)
- {
- _database = client.GetDatabase(databaseName);
- }
- }
- #region SELECT
- /// <summary>
- /// 根据查询条件, 获取数据
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="id"></param>
- /// <returns></returns>
- public List<T> GetList<T>(Expression<Func<T, bool>> conditions = null)
- {
- var collection = _database.GetCollection<T>(typeof(T).Name);
- if (conditions != null)
- {
- return collection.Find(conditions).ToList();
- }
- return collection.Find(_ => true).ToList();
- }#endregion
- #region INSERT/// <summary>
- /// 插入多条数据, 数据用 list 表示
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="list"></param>
- /// <returns></returns>
- public List<T> InsertMany<T>(List<T> list)
- {
- var collection = _database.GetCollection<T>(typeof(T).Name);
- collection.InsertMany(list);
- return list;
- }
- #endregion
- }
第三步: 新建一个 ASP.NET core webapi 项目, 引用此类库进行演示
在项目中的 appsetting.JSON 添加 MongoDB 的连接字符串: 我在这边使用自定义的一个数据名称 testdb, 在插入 MongoDB 的时候会会自动在创建数据库和集合以及文档. 接着往下看
- "MongoConnection": { //MongoDB 数据库连接
- "ConnectionString": "mongodb://127.0.0.1:27017",
- "Database": "testdb",
- "IsSSL": true
- },
第四步: 新建一个 MongoDB 测试控制器, 展示了插入单条和多条以及查询的接口.
- [Produces("application/json")]
- [Route("api/MongoDB/[action]")]
- public class MongoDBController : Controller
- {
- private readonly MongoDBBase _context = null;
- public MongoDBController(IOptions<Settings> settings)
- {
- _context = new MongoDBBase(settings.Value.ConnectionString, settings.Value.Database);
- }
- [HttpGet]
- public IActionResult AddList()
- {
- List<MongoDBPostTest> list = new List<MongoDBPostTest>()
- {
- new MongoDBPostTest()
- {
- Id = "2",
- Body = "Test note 3",
- UpdatedOn = DateTime.Now,
- UserId = 1,
- HeaderImage = new NoteImage
- {
- ImageSize = 10,
- Url = "http://localhost/image1.png",
- ThumbnailUrl = "http://localhost/image1_small.png"
- }
- },
- new MongoDBPostTest()
- {
- Id = "3",
- Body = "Test note 4",
- UpdatedOn = DateTime.Now,
- UserId = 1,
- HeaderImage = new NoteImage
- {
- ImageSize = 14,
- Url = "http://localhost/image3.png",
- ThumbnailUrl = "http://localhost/image3_small.png"
- }
- }
- };
- try
- {
- _context.InsertMany(list);
- }
- catch (Exception ex)
- {
- throw;
- }
- return Ok("成功");
- }
- [HttpGet]
- public Result<List<MongoDBPostTest>> SelectSingle()
- {
- // 无条件
- var list = _context.GetList<MongoDBPostTest>();
- // 有条件
- //var list = _context.GetList<MongoDBPostTest>(a => a.Id == "1");
- // 得到单条数据, 无条件
- //var list = _context.GetSingle<MongoDBPostTest>();
- // 得到单条数据, 有条件
- //var list = _context.GetSingle<MongoDBPostTest>(a => a.Id == "3");
- ObjectId internalId = _context.GetInternalId("5bbf41651d3b66668cbb5bfc");
- var a = _context.GetSingle<MongoDBPostTest>(note => note.Id == "5bbf41651d3b66668cbb5bfc" || note.InternalId == internalId);
- return ResHelper.Suc(1, list, "成功");
- }
- }
测试类
- public class MongoDBPostTest
- {
- [BsonId]
- // standard BSonId generated by MongoDB
- public ObjectId InternalId { get; set; }
- public string Id { get; set; }
- public string Body { get; set; } = string.Empty;
- [BsonDateTimeOptions]
- public DateTime UpdatedOn { get; set; } = DateTime.Now;
- public NoteImage HeaderImage { get; set; }
- public int UserId { get; set; } = 0;
- }
- public class NoteImage
- {
- public string Url { get; set; } = string.Empty;
- public string ThumbnailUrl { get; set; } = string.Empty;
- public long ImageSize { get; set; } = 0L;
- }
第五步: 运行项目, 执行一下.
我们执行一下插入多条的数据吧, 执行成功.
然后我们看一下数据库, 发现已经生成了一个 testdb 数据库, 里面包含了我们的数据内容
然后我们执行以下查的操作: 把我们刚才插入的数据返回回来了.
注意: 这边有一个坑有待解决, 就是 MongoDB 存储的时间是 UTC, 会跟我们的本地时间相差 8 个小时. 因此这边需要特殊处理一下时间.
三, 总结
至此, MongoDB 的简单运用已演示完毕, 后期大家根据官方文档可进行扩展, 越扩展到后面, 会觉得越来越有意思. 感谢大家的支持. Thank you.
参考文档:
MongoDB 教程: http://www.runoob.com/mongodb/mongodb-tutorial.html
MongoDB 中文手册: http://www.mongoing.com/docs/
好了, 以上就是这篇文章的全部内容了, 希望本文的内容对大家的学习或者工作具有一定的参考学习价值, 如果有疑问大家可以留言交流, 谢谢大家对脚本之家的支持.
来源: https://www.jb51.net/article/148751.htm