当前位置:Gxlcms > 数据库问题 > c#简单操作MongoDB_2.4

c#简单操作MongoDB_2.4

时间:2021-07-01 10:21:17 帮助过:10人阅读

  1. using System.ComponentModel;
  2. namespace Models
  3. {
  4. /// <summary>
  5. /// Copyright (C) 2017 yjq 版权所有。
  6. /// 类名:ProductSaleState.cs
  7. /// 类属性:公共类(非静态)
  8. /// 类功能描述:商品销售状态
  9. /// 创建标识:yjq 2017/5/21 0:36:02
  10. /// </summary>
  11. public enum ProductSaleState
  12. {
  13. /// <summary>
  14. /// 待审核
  15. /// </summary>
  16. [Description("待审核")]
  17. WaitingCheck = 1,
  18. /// <summary>
  19. /// 上架
  20. /// </summary>
  21. [Description("上架")]
  22. OnSale = 2,
  23. /// <summary>
  24. /// 下架
  25. /// </summary>
  26. [Description("下架")]
  27. OffShelves = 3,
  28. /// <summary>
  29. /// 已销售
  30. /// </summary>
  31. [Description("已销售")]
  32. Saled = 4
  33. }
  34. }
  35. using System.ComponentModel;
  36. namespace Models
  37. {
  38. /// <summary>
  39. /// Copyright (C) 2017 yjq 版权所有。
  40. /// 类名:CommentCheckState.cs
  41. /// 类属性:公共类(非静态)
  42. /// 类功能描述:评论审核状态
  43. /// 创建标识:yjq 2017/5/21 0:51:43
  44. /// </summary>
  45. public enum CommentCheckState
  46. {
  47. /// <summary>
  48. /// 待审核
  49. /// </summary>
  50. [Description("待审核")]
  51. WaitingCheck = 1,
  52. /// <summary>
  53. /// 审核通过
  54. /// </summary>
  55. [Description("审核通过")]
  56. Passed = 2,
  57. /// <summary>
  58. /// 审核不通过
  59. /// </summary>
  60. [Description("审核不通过")]
  61. NotPass = 3
  62. }
  63. }
  64. using Infrastructure;
  65. using MongoDB.Bson;
  66. using MongoDB.Bson.Serialization.Attributes;
  67. using System;
  68. using System.Collections.Generic;
  69. namespace Models
  70. {
  71. /// <summary>
  72. /// Copyright (C) 2015 备胎 版权所有。
  73. /// 类名:Product.cs
  74. /// 类属性:公共类(非静态)
  75. /// 类功能描述:商品
  76. /// 创建标识:yjq 2017/5/18 14:59:35
  77. /// </summary>
  78. public sealed class Product
  79. {
  80. public Product()
  81. {
  82. }
  83. public Product(string name, decimal price) : this()
  84. {
  85. Id = ObjectId.GenerateNewId();
  86. Name = name;
  87. Price = price;
  88. SaleState = ProductSaleState.WaitingCheck;
  89. CreateTime = DateTime.Now;
  90. }
  91. /// <summary>
  92. /// 商品ID
  93. /// </summary>
  94. [BsonElement(elementName: "_id")]
  95. public ObjectId Id { get; set; }
  96. /// <summary>
  97. /// 商品名字
  98. /// </summary>
  99. public string Name { get; set; }
  100. /// <summary>
  101. /// 价格
  102. /// </summary>
  103. public decimal? Price { get; set; }
  104. /// <summary>
  105. /// 销售状态
  106. /// </summary>
  107. public ProductSaleState SaleState { get; set; }
  108. /// <summary>
  109. /// 添加时间
  110. /// </summary>
  111. [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
  112. public DateTime CreateTime { get; set; }
  113. /// <summary>
  114. /// 修改时间
  115. /// </summary>
  116. [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
  117. public DateTime? ModifyTime { get; set; }
  118. /// <summary>
  119. /// 商品评论
  120. /// </summary>
  121. public List<ProductComment> Comments { get; set; }
  122. public override string ToString()
  123. {
  124. return $"{Id}:{Name},价格{Price}元,审核状态{SaleState.Desc()}";
  125. }
  126. }
  127. }
  128. using Infrastructure;
  129. using MongoDB.Bson;
  130. using MongoDB.Bson.Serialization.Attributes;
  131. using System;
  132. namespace Models
  133. {
  134. /// <summary>
  135. /// Copyright (C) 2015 备胎 版权所有。
  136. /// 类名:ProductComment.cs
  137. /// 类属性:公共类(非静态)
  138. /// 类功能描述:商品评论
  139. /// 创建标识:yjq 2017/5/18 15:08:32
  140. /// </summary>
  141. public sealed class ProductComment
  142. {
  143. /// <summary>
  144. /// 评论ID
  145. /// </summary>
  146. [BsonElement(elementName: "_id")]
  147. public ObjectId Id { get; set; }
  148. /// <summary>
  149. /// 评论内容
  150. /// </summary>
  151. public string Content { get; set; }
  152. /// <summary>
  153. /// 评论审核状态
  154. /// </summary>
  155. public CommentCheckState CheckState { get; set; }
  156. /// <summary>
  157. /// 添加时间
  158. /// </summary>
  159. [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
  160. public DateTime CreateTime { get; set; }
  161. /// <summary>
  162. /// 修改时间
  163. /// </summary>
  164. [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
  165. public DateTime? ModifyTime { get; set; }
  166. public override string ToString()
  167. {
  168. return $"评论信息:{Content},审核状态:{CheckState.Desc()}";
  169. }
  170. }
  171. }
技术分享图片

  2、我们先进行新增一个苹果,价格为5.2,且审核状态为待审核的,然后在查询商品列表,输出所有的商品,并显示出其状态

  技术分享图片 技术分享图片
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using MongoDB.Driver;
  7. using Models;
  8. using MongoDB.Bson;
  9. namespace MongoDbTest
  10. {
  11. class Program
  12. {
  13. private static string _MongoDbConnectionStr = "mongodb://yjq:123456@localhost:27017/admin";
  14. static void Main(string[] args)
  15. {
  16. var productCollection = GetCollection<Product>();
  17. //添加一个待审核的商品
  18. Product product = new Product("苹果", (decimal)5.20);
  19. productCollection.InsertOne(product);
  20. Console.WriteLine($"添加商品:{product.ToString()}成功。");
  21. var productList = productCollection.Find(new BsonDocument()).ToList();
  22. foreach (var item in productList)
  23. {
  24. Console.WriteLine(item.ToString());
  25. }
  26. Console.Read();
  27. }
  28. private static IMongoCollection<T> GetCollection<T>(string collectionName = null)
  29. {
  30. MongoUrl mongoUrl = new MongoUrl(_MongoDbConnectionStr);
  31. var mongoClient = new MongoClient(mongoUrl);
  32. var database = mongoClient.GetDatabase(mongoUrl.DatabaseName);
  33. return database.GetCollection<T>(collectionName ?? typeof(T).Name);
  34. }
  35. }
  36. }
技术分享图片

  技术分享图片

  用robomongodb打开,然后查看对应信息,我们会发现数据库里面存储的时间比我们的当前时间晚8小时,这是因为在安装mongodb的时候,默认的时区不是我们本地的时区导致的,但是只要在时间字段上标记[BsonDateTimeOptions(Kind = DateTimeKind.Local)]就可以在输出的时候显示我们本地时间了。

  技术分享图片

 

 

到这里,我们就完成了简单的新增和查询功能,接下来我们先随机插入几个审核通过、不通过、待审核的商品共100个。

代码如下:

 更改product代码

  技术分享图片 技术分享图片
  1. using Infrastructure;
  2. using MongoDB.Bson;
  3. using MongoDB.Bson.Serialization.Attributes;
  4. using System;
  5. using System.Collections.Generic;
  6. namespace Models
  7. {
  8. /// <summary>
  9. /// Copyright (C) 2015 备胎 版权所有。
  10. /// 类名:Product.cs
  11. /// 类属性:公共类(非静态)
  12. /// 类功能描述:商品
  13. /// 创建标识:yjq 2017/5/18 14:59:35
  14. /// </summary>
  15. public sealed class Product
  16. {
  17. public Product()
  18. {
  19. }
  20. public Product(string name, decimal price) : this(name, price, ProductSaleState.WaitingCheck)
  21. {
  22. }
  23. public Product(string name, decimal price, ProductSaleState saleState)
  24. {
  25. Id = ObjectId.GenerateNewId();
  26. Name = name;
  27. Price = price;
  28. SaleState = saleState;
  29. CreateTime = DateTime.Now;
  30. }
  31. /// <summary>
  32. /// 商品ID
  33. /// </summary>
  34. [BsonElement(elementName: "_id")]
  35. public ObjectId Id { get; set; }
  36. /// <summary>
  37. /// 商品名字
  38. /// </summary>
  39. public string Name { get; set; }
  40. /// <summary>
  41. /// 价格
  42. /// </summary>
  43. public decimal? Price { get; set; }
  44. /// <summary>
  45. /// 销售状态
  46. /// </summary>
  47. public ProductSaleState SaleState { get; set; }
  48. /// <summary>
  49. /// 添加时间
  50. /// </summary>
  51. [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
  52. public DateTime CreateTime { get; set; }
  53. /// <summary>
  54. /// 修改时间
  55. /// </summary>
  56. [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
  57. public DateTime? ModifyTime { get; set; }
  58. /// <summary>
  59. /// 商品评论
  60. /// </summary>
  61. public List<ProductComment> Comments { get; set; }
  62. public override string ToString()
  63. {
  64. return $"{Id}:{Name},价格{Price}元,审核状态{SaleState.Desc()}";
  65. }
  66. }
  67. }
技术分享图片   技术分享图片 技术分享图片
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using MongoDB.Driver;
  7. using Models;
  8. using MongoDB.Bson;
  9. namespace MongoDbTest
  10. {
  11. class Program
  12. {
  13. private static string _MongoDbConnectionStr = "mongodb://yjq:123456@localhost:27017/admin";
  14. static void Main(string[] args)
  15. {
  16. var productCollection = GetCollection<Product>();
  17. //添加一个待审核的商品
  18. //Product product = new Product("苹果", (decimal)5.20);
  19. //productCollection.InsertOne(product);
  20. //Console.WriteLine($"添加商品:{product.ToString()}成功。");
  21. //批量增加商品
  22. List<Product> productAddList = new List<Product>();
  23. for (int i = 0; i < 100; i++)
  24. {
  25. productAddList.Add(GetRandomProduct());
  26. }
  27. productCollection.InsertMany(productAddList);
  28. var productList = productCollection.Find(new BsonDocument()).ToList();
  29. foreach (var item in productList)
  30. {
  31. Console.WriteLine(item.ToString());
  32. }
  33. Console.Read();
  34. }
  35. private static IMongoCollection<T> GetCollection<T>(string collectionName = null)
  36. {
  37. MongoUrl mongoUrl = new MongoUrl(_MongoDbConnectionStr);
  38. var mongoClient = new MongoClient(mongoUrl);
  39. var database = mongoClient.GetDatabase(mongoUrl.DatabaseName);
  40. return database.GetCollection<T>(collectionName ?? typeof(T).Name);
  41. }
  42. private static string[] _ProductNames = new string[] { "苹果", "香蕉", "菠萝", "哈密瓜", "西瓜", "黄瓜", "草莓", "桃子", "芒果", "猕猴桃", "梨" };
  43. private static Random rn = new Random();
  44. private static Product GetRandomProduct()
  45. {
  46. var i = rn.Next(_ProductNames.Length);
  47. decimal price = i * 15;
  48. var enumValue = rn.Next(1, 5);
  49. return new Product(_ProductNames[i], price, (ProductSaleState)enumValue);
  50. }
  51. }
  52. }
技术分享图片

然后运行,可以去robo查看结果,发现数据库里面总共有101条数据

技术分享图片

批量增加的操作也执行了,那么接下来我们就继续执行分页和修改删除的功能。

首先我们先查询返回总记录数和前20条商品信息的内容:

  技术分享图片 Program

技术分享图片

因为商品是随机产生的,所以可能导致你我之间的结果不一样。

接下来我们查询待审核的商品,并显示待审核的商品总数,我们更改下filte(使用lambda表达式树比较方便),二选一都可以

  技术分享图片 技术分享图片
  1. Expression<Func<Product, bool>> expression = m => m.SaleState == ProductSaleState.WaitingCheck;
  2. long productAllCount = productCollection.Count(expression);
  3. var productList = productCollection.Find(expression).Skip(0).Limit(20).ToList();
  4. Console.ForegroundColor = ConsoleColor.Red;
  5. Console.WriteLine($"总记录数为{productAllCount.ToString()}");
  6. Console.ForegroundColor = ConsoleColor.Blue;
  7. Console.WriteLine("前20条商品信息为:");
  8. Console.ForegroundColor = ConsoleColor.White;
  9. foreach (var item in productList)
  10. {
  11. Console.WriteLine(item.ToString());
  12. }
技术分享图片 技术分享图片 技术分享图片
  1. #region 待审核 filter构建
  2. var filter = Builders<Product>.Filter.Eq("SaleState", ProductSaleState.WaitingCheck);
  3. long productAllCount = productCollection.Count(filter);
  4. var productList = productCollection.Find(filter).Skip(0).Limit(20).ToList();
  5. Console.ForegroundColor = ConsoleColor.Red;
  6. Console.WriteLine($"总记录数为{productAllCount.ToString()}");
  7. Console.ForegroundColor = ConsoleColor.Blue;
  8. Console.WriteLine("前20条商品信息为:");
  9. Console.ForegroundColor = ConsoleColor.White;
  10. foreach (var item in productList)
  11. {
  12. Console.WriteLine(item.ToString());
  13. }
  14. #endregion
技术分享图片

技术分享图片

接下来我们对第1条待审核的商品进行审核通过的操作,并增加一条“哇,这个好好吃啊!”的评论。

  技术分享图片 技术分享图片
  1. using Infrastructure;
  2. using MongoDB.Bson;
  3. using MongoDB.Bson.Serialization.Attributes;
  4. using System;
  5. using System.Collections.Generic;
  6. namespace Models
  7. {
  8. /// <summary>
  9. /// Copyright (C) 2015 备胎 版权所有。
  10. /// 类名:Product.cs
  11. /// 类属性:公共类(非静态)
  12. /// 类功能描述:商品
  13. /// 创建标识:yjq 2017/5/18 14:59:35
  14. /// </summary>
  15. public sealed class Product
  16. {
  17. public Product()
  18. {
  19. }
  20. public Product(string name, decimal price) : this(name, price, ProductSaleState.WaitingCheck)
  21. {
  22. }
  23. public Product(string name, decimal price, ProductSaleState saleState)
  24. {
  25. Id = ObjectId.GenerateNewId();
  26. Name = name;
  27. Price = price;
  28. SaleState = saleState;
  29. CreateTime = DateTime.Now;
  30. }
  31. /// <summary>
  32. /// 商品ID
  33. /// </summary>
  34. [BsonElement(elementName: "_id")]
  35. public ObjectId Id { get; set; }
  36. /// <summary>
  37. /// 商品名字
  38. /// </summary>
  39. public string Name { get; set; }
  40. /// <summary>
  41. /// 价格
  42. /// </summary>
  43. public decimal? Price { get; set; }
  44. /// <summary>
  45. /// 销售状态
  46. /// </summary>
  47. public ProductSaleState SaleState { get; set; }
  48. /// <summary>
  49. /// 添加时间
  50. /// </summary>
  51. [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
  52. public DateTime CreateTime { get; set; }
  53. /// <summary>
  54. /// 修改时间
  55. /// </summary>
  56. [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
  57. public DateTime? ModifyTime { get; set; }
  58. /// <summary>
  59. /// 商品评论
  60. /// </summary>
  61. public List<ProductComment> Comments { get; set; }
  62. public override string ToString()
  63. {
  64. return $"{Id}:{Name},价格{Price}元,审核状态{SaleState.Desc()}";
  65. }
  66. public void ShowComments()
  67. {
  68. if (Comments != null)
  69. {
  70. foreach (var item in Comments)
  71. {
  72. Console.WriteLine(item.ToString());
  73. }
  74. }
  75. }
  76. public void Comment(string content)
  77. {
  78. if (Comments == null)
  79. {
  80. Comments = new List<Models.ProductComment>();
  81. }
  82. Comments.Add(new Models.ProductComment(content));
  83. }
  84. }
  85. }
技术分享图片   技术分享图片 技术分享图片
  1. using Infrastructure;
  2. using MongoDB.Bson;
  3. using MongoDB.Bson.Serialization.Attributes;
  4. using System;
  5. namespace Models
  6. {
  7. /// <summary>
  8. /// Copyright (C) 2015 备胎 版权所有。
  9. /// 类名:ProductComment.cs
  10. /// 类属性:公共类(非静态)
  11. /// 类功能描述:商品评论
  12. /// 创建标识:yjq 2017/5/18 15:08:32
  13. /// </summary>
  14. public sealed class ProductComment
  15. {
  16. public ProductComment(string content)
  17. {
  18. if (content == null)
  19. {
  20. throw new ArgumentNullException("content");
  21. }
  22. Id = ObjectId.GenerateNewId();
  23. Content = content;
  24. CheckState = CommentCheckState.WaitingCheck;
  25. CreateTime = DateTime.Now;
  26. }
  27. /// <summary>
  28. /// 评论ID
  29. /// </summary>
  30. [BsonElement(elementName: "_id")]
  31. public ObjectId Id { get; set; }
  32. /// <summary>
  33. /// 评论内容
  34. /// </summary>
  35. public string Content { get; set; }
  36. /// <summary>
  37. /// 评论审核状态
  38. /// </summary>
  39. public CommentCheckState CheckState { get; set; }
  40. /// <summary>
  41. /// 添加时间
  42. /// </summary>
  43. [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
  44. public DateTime CreateTime { get; set; }
  45. /// <summary>
  46. /// 修改时间
  47. /// </summary>
  48. [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
  49. public DateTime? ModifyTime { get; set; }
  50. public override string ToString()
  51. {
  52. return $"评论信息:{Content},审核状态:{CheckState.Desc()}";
  53. }
  54. }
  55. }
技术分享图片   技术分享图片 技术分享图片
  1. var beforeUpdateProduct = productCollection.Find(m => m.SaleState == ProductSaleState.WaitingCheck).FirstOrDefault();
  2. Console.WriteLine($"更新前信息{beforeUpdateProduct?.ToString()}");
  3. //注意线程安全,这里只是做演示
  4. beforeUpdateProduct.Comment("哇,这个好好吃啊!");
  5. var updateFilter = Builders<Product>.Update.Set(m => m.SaleState, ProductSaleState.OnSale).Set(m => m.ModifyTime, DateTime.Now).Set(m => m.Comments, beforeUpdateProduct.Comments);
  6. var updateResult = productCollection.UpdateOne(m => m.Id == beforeUpdateProduct.Id, updateFilter);
  7. if (updateResult.IsModifiedCountAvailable)
  8. {
  9. var afterUpdateProduct = productCollection.Find(m => m.Id == beforeUpdateProduct.Id).FirstOrDefault();
  10. Console.WriteLine("更新销售状态成功=====");
  11. Console.WriteLine($"更新后信息{afterUpdateProduct?.ToString()}");
  12. Console.WriteLine("评论信息:");
  13. afterUpdateProduct.ShowComments();
  14. }
  15. else
  16. {
  17. Console.WriteLine("更新失败=====");
  18. }
技术分享图片

技术分享图片

下一步我们查找有评论待审核的商品列表

  技术分享图片
  1. var commentWaitingCheckProducts = productCollection.Find(m => m.Comments.Where(k => k.CheckState == CommentCheckState.WaitingCheck).Any()).ToEnumerable();
  2. foreach (var item in commentWaitingCheckProducts)
  3. {
  4. Console.WriteLine(item.ToString());
  5. }
  技术分享图片 技术分享图片
  1. var projection = Builders<Product>.Projection.Expression(m => new ProductDto
  2. {
  3. Comments = m.Comments,
  4. Id = m.Id,
  5. Name = m.Name,
  6. Price = m.Price,
  7. SaleState = m.SaleState
  8. });
  9. var commentWaitingCheckProducts = productCollection.Find(m => m.Comments.Where(k => k.CheckState == CommentCheckState.WaitingCheck).Any()).Project(projection).ToEnumerable();
  10. foreach (var item in commentWaitingCheckProducts)
  11. {
  12. Console.WriteLine(item.ToString());
  13. }
技术分享图片

简单的操作就到这里了,其它的一些操作可以根据文档来,驱动对lambda的支持可以让我们更加容易上手查询一些条件难的查询。

Api文档地址,该示例源码下载

c#简单操作MongoDB_2.4

标签:tran   pre   builder   mongo   build   attr   tps   显示   lis   

人气教程排行