愚公系列2022年05月 .NET架构班 059-分布式中间件 .Net Core下使用Mongodb的封装

网友投稿 672 2022-05-29

一、Mongodb的基本概念

1.Mongodb的数据结构

2.Mongodb数据类型

MongoDB的最小存储单位就是文档(document)对象。文档(document)对象对应于关系型数据库的行。数据在MongoDB中以BSON(Binary-JSON)文档的格式存储在磁盘上。

BSON(Binary Serialized Document Format)是一种类json的一种二进制形式的存储格式,简称Binary JSON。BSON和JSON一样,支持内嵌的文档对象和数组对象,但是BSON有JSON没有的一些数据类型,如Date和BinData类型。

二、Mongodb的代码封装

1.配置文件

【愚公系列】2022年05月 .NET架构班 059-分布式中间件 .Net Core下使用Mongodb的封装

{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "ProductMongoDBOptions": { "ConnectionString": "mongodb://localhost:27017", "DatabaseName": "ProductDb_3", "ProductCollectionName": "Product_3" }, "AllowedHosts": "*" }

2.扩展类

///

/// MongoDB扩展方法 /// public static class MongoDBServiceCollectionExtensions { public static IServiceCollection AddMongoDB(this IServiceCollection services, IConfiguration Configuration) { // 1、获取配置文件数据 ProductMongoDBOptions productMongoDBOptions = (ProductMongoDBOptions)Configuration.GetSection(nameof(ProductMongoDBOptions)); // 1、建立MongoDB连接 var client = new MongoClient(productMongoDBOptions.ConnectionString); // 2、获取商品库 var database = client.GetDatabase(productMongoDBOptions.DatabaseName); // 3、获取商品表(集合) var _products = database.GetCollection(productMongoDBOptions.ProductCollectionName); services.AddSingleton(_products); return services; } }

3.注入扩展类

services.AddMongoDB();

4.使用

4.1 相关依赖

public class Product { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { set; get; } public string ProductCode { set; get; } //商品编码 public string ProductUrl { set; get; } // 商品主图 public string ProductTitle { set; get; } //商品标题 public string ProductDescription { set; get; } // 图文描述 public decimal ProductVirtualprice { set; get; } // 商品虚拟价格 public decimal ProductPrice { set; get; } //价格 public int ProductSort { set; get; } //商品序号 public int ProductSold { set; get; } //已售件数 public int ProductStock { set; get; } //商品库存 public string ProductStatus { set; get; } // 商品状态 public int score { set; get; } //商品级别 }

public interface IProductService { void Create(Product Product); public void CreateList(List Products); IEnumerable GetProducts(); Product GetProductById(string id); public IEnumerable GetProductsByPage(int Page, int PageSize); public IEnumerable GetProductsBySort(Product product, int Page, int PageSize); public IEnumerable GetProductsByAggregation(Product product); void Update(string id,Product Product); public void UpdateList(string id, Product Product); // 更新字段 public void UpdateFiled(string id, ProductUpdateFiledDto productUpdateFiledDto); void Delete(Product Product); public void DeleteList(Product Product); bool ProductExists(string id); // 字段修改 public void Replace(string id, Product Product); // 创建索引 public string CreateIndex(); }

///

/// 商品服务实现 /// public class ProductService : IProductService { private readonly IMongoCollection _products; public ProductService( /* IMongoCollection products,*/ IConfiguration configuration/*,IOptions options*/) { // 1、建立MongoDB连接 //var client = new MongoClient("mongodb://localhost:27018,localhost:27019,localhost:27020"); var client = new MongoClient("mongodb://localhost:27000,localhost:27100"); // 2、获取商品库(自己创建商品数据) var database = client.GetDatabase("ProductDb"); // 3、获取商品表(自己创建商品数) _products = database.GetCollection("Product"); // _products = products; } public void Create(Product Product) { _products.InsertOne(Product); } public void CreateList(List Products) { _products.InsertMany(Products); } public void Delete(Product Product) { _products.DeleteOne(product => product.Id == Product.Id); } public void DeleteList(Product Product) { _products.DeleteMany(product => product.Id == Product.Id); } public Product GetProductById(string id) { return _products.Find(product => product.Id == id).FirstOrDefault(); } public IEnumerable GetProducts() { return _products.Find(product => true).ToList(); } /// /// 商品不同字段获取 /// /// public IEnumerable GetProductsFiled() { var filter = Builders.Filter; /* BsonDocument filter = new BsonDocument(); var collection = _mongoDatabase.GetCollection("ProductDb"); var s = collection.Find(filter).ToList(); using (var cursor = collection.FindAsync(filter).Result) { while (cursor.MoveNextAsync().Result) { var batch = cursor.Current; foreach (BsonDocument document in batch) { Console.WriteLine(document.ToJson()); } } }*/ return _products.Find(product => true).ToList(); } /*/// /// 商品数量查询 /// /// /// public long GetCount(int Page, int PageSize) { var skip = (Page - 1) * PageSize; return _products.Count(); }*/ /// /// 商品分页查询 /// /// /// public IEnumerable GetProductsByPage(int Page,int PageSize) { var skip = (Page - 1) * PageSize; return _products.Find(x => true).Skip(skip).Limit(PageSize).ToList(); } /// /// 商品排序 /// /// /// public IEnumerable GetProductsBySort(Product product, int Page, int PageSize) { var skip = (Page - 1) * PageSize; return _products.Find(product => true).SortBy(product => product.ProductSort).ToList(); } /// /// 商品价格聚合查询 /// /// /// public IEnumerable GetProductsByAggregation(Product product) { var filter = Builders.Filter; PipelineDefinition pipelineDefinitions = PipelineDefinition.Create("ProductPrice"); var ints = _products.Aggregate(pipelineDefinitions); while (ints.MoveNext()) { var test = ints.Current; return test; } return null; } /// /// 更新 /// /// /// public void Update(string id, Product Product) { var update = Builders.Update; _products.UpdateOne(product => product.Id == id, update.Set("ProductTitle", Product.ProductTitle)); } /// /// 更新字段(增加字段) /// /// /// public void UpdateFiled(string id, ProductUpdateFiledDto productUpdateFiledDto) { var update = Builders.Update; _products.UpdateOne(product => product.Id == id, update.AddToSet("ProductTest", productUpdateFiledDto.ProductLike)); } /// /// 批量更新 /// /// /// public void UpdateList(string id, Product Product) { var filter = Builders.Filter; var update = Builders.Update; _products.UpdateMany(product => product.ProductCode == Product.ProductCode, update.Set("ProductTitle", Product.ProductTitle)); } /// /// 创建索引 /// /// public string CreateIndex() { var indexKeys = Builders.IndexKeys; return _products.Indexes.CreateOne(indexKeys.Descending("ProductCode")); } // 原理 // 分片集群 // 分片复制集群 /// /// 替换 /// /// /// public void Replace(string id, Product Product) { _products.ReplaceOneAsync(x => x.Id == id, Product); } public bool ProductExists(string id) { Product product = _products.Find(product => product.Id == id).FirstOrDefault(); if (product != null) { return true; } return false; } }

4.使用

///

/// 商品控制器 /// [ApiController] [Route("Product")] public class ProductController : ControllerBase { private readonly ILogger _logger; private readonly IProductService _productService; public ProductController(ILogger logger, IProductService productService) { _logger = logger; _productService = productService; } /// /// 添加商品 /// /// /// [HttpPost] public ActionResult CreateProduct(Product product) { _productService.Create(product); return CreatedAtAction("GetProduct", new { id = product.Id }, product); } /// /// 批量添加商品 /// /// /// [HttpPost("ProductList")] public ActionResult CreateProductList(Product[] Products) { _productService.CreateList(Products.ToList()); return CreatedAtAction("GetProduct", Products); } /// /// 查询商品列表 /// /// [HttpGet] public ActionResult> GetProducts() { return _productService.GetProducts().ToList(); } /// /// 商品单个商品 /// /// /// [HttpGet("{id}")] public ActionResult GetProduct(string id) { var product = _productService.GetProductById(id); if (product == null) { return NotFound(); } return product; } /// /// 商品分页查询 /// /// /// /// [HttpGet("Page")] public ActionResult> GetProductsByPage(int Page ,int PageSize) { return _productService.GetProductsByPage(Page, PageSize).ToList(); } [HttpGet("Aggregation")] public ActionResult> GetProductsByAggregation(Product product) { return _productService.GetProductsByAggregation(product).ToList(); } /// /// 修改商品 /// /// /// /// [HttpPut("{id}")] public IActionResult PutProduct(string id, Product product) { try { _productService.Update(id,product); } catch (Exception) { throw; } return NoContent(); } /// /// 修改商品 /// /// /// /// [HttpPut("UpdateField")] public IActionResult PutFieldProduct(string id, ProductUpdateFiledDto productUpdateFiledDto) { try { _productService.UpdateFiled(id, productUpdateFiledDto); } catch (Exception) { throw; } return NoContent(); } /// /// 商品文档批量修改 /// /// /// /// [HttpPut("UpdateList")] public IActionResult PutProductList(string id, Product product) { try { _productService.UpdateList(id, product); } catch (Exception) { throw; } return NoContent(); } /// /// 删除商品 /// /// /// [HttpDelete] public IActionResult DeletetProduct(Product product) { try { _productService.Delete(product); } catch (Exception) { throw; } return NoContent(); } // PUT: api/Products/5 [HttpPost("CreateIndex")] public IActionResult CreateIndex() { try { _productService.CreateIndex(); } catch (Exception) { throw; } return NoContent(); } }

.NET MongoDB 分布式

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:写给鲜枣课堂粉丝的一封信
下一篇:使用 Python 和 PyQt 构建批量文件重命名工具
相关文章