MongoDBTools.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. using Amazon.Runtime.Internal;
  2. using Business.Core.Attributes;
  3. using Microsoft.Extensions.Options;
  4. using MongoDB.Bson;
  5. using MongoDB.Bson.Serialization.Attributes;
  6. using MongoDB.Driver;
  7. using MongoDB.Driver.Linq;
  8. using System;
  9. using System.Collections;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Linq.Expressions;
  13. using System.Reflection;
  14. using System.Text;
  15. using System.Threading.Tasks;
  16. using Volo.Abp.Domain.Entities;
  17. using Volo.Abp.Domain.Repositories;
  18. namespace Business.Core.MongoDBHelper
  19. {
  20. /// <summary>
  21. /// MongoDB帮助类
  22. /// </summary>
  23. public class MongoDBTools<T> : IMongoDB<T>
  24. {
  25. public readonly IMongoCollection<T> mongoCollection;
  26. public readonly IMongoDatabase dataBase;
  27. public IOptionsSnapshot<Config> _config;
  28. public CollectionNameAttribute collectonName;
  29. /// <summary>
  30. /// MongoDB链接
  31. /// </summary>
  32. /// <param name="config"></param>
  33. /// <exception cref="NotImplementedException"></exception>
  34. public MongoDBTools(IOptionsSnapshot<Config> config)
  35. {
  36. _config = config;
  37. collectonName = typeof(T).GetCustomAttributes(typeof(CollectionNameAttribute), true).FirstOrDefault() as CollectionNameAttribute;
  38. if (collectonName == null)
  39. {
  40. throw new NotImplementedException("请配置Attribute属性!");
  41. }
  42. //数据库链接
  43. MongoClient client = new MongoClient(config.Value.connectstring + collectonName.DatabaseName);
  44. //数据库
  45. dataBase = client.GetDatabase(collectonName.DatabaseName);
  46. //表名
  47. mongoCollection = dataBase.GetCollection<T>(collectonName.CollectionName);
  48. }
  49. /// <summary>
  50. /// 插入一条数据
  51. /// </summary>
  52. /// <param name="document"></param>
  53. /// <returns></returns>
  54. public Task InsertOne(T document)
  55. {
  56. return mongoCollection.InsertOneAsync(document);
  57. }
  58. /// <summary>
  59. /// 插入多条数据
  60. /// </summary>
  61. /// <param name="documents"></param>
  62. /// <returns></returns>
  63. /// <exception cref="NotImplementedException"></exception>
  64. public Task InsertMany(List<T> documents)
  65. {
  66. return mongoCollection.InsertManyAsync(documents,new InsertManyOptions() { IsOrdered = false});
  67. }
  68. /// <summary>
  69. /// 获取所有数据
  70. /// </summary>
  71. /// <returns></returns>
  72. /// <exception cref="NotImplementedException"></exception>
  73. public Task<List<T>> GetAll()
  74. {
  75. return mongoCollection.AsQueryable<T>().ToListAsync();
  76. }
  77. /// <summary>
  78. /// 根据条件获取数据
  79. /// </summary>
  80. /// <returns></returns>
  81. public Task<List<T>> GetManyByCondition(Expression<Func<T, bool>> filter)
  82. {
  83. return mongoCollection.Find(filter).ToListAsync();
  84. }
  85. /// <summary>
  86. /// 根据条件获取数据
  87. /// </summary>
  88. /// <returns></returns>
  89. public Task<List<T>> GetManyByIds(FilterDefinition<T> filter)
  90. {
  91. return mongoCollection.Find(filter).ToListAsync();
  92. }
  93. /// <summary>
  94. /// 删除数据
  95. /// </summary>
  96. /// <param name="expression"></param>
  97. /// <param name="isOne"></param>
  98. /// <returns></returns>
  99. public Task<DeleteResult> Delete(Expression<Func<T, bool>> expression, bool isOne = false)
  100. {
  101. if (isOne)
  102. return mongoCollection.DeleteOneAsync(expression);
  103. else
  104. return mongoCollection.DeleteManyAsync(expression);
  105. }
  106. /// <summary>
  107. /// 删除数据
  108. /// </summary>
  109. /// <param name="filter"></param>
  110. /// <param name="isOne"></param>
  111. /// <returns></returns>
  112. public Task<DeleteResult> Delete(FilterDefinition<T> filter, bool isOne = false)
  113. {
  114. if (isOne)
  115. return mongoCollection.DeleteOneAsync(filter);
  116. else
  117. return mongoCollection.DeleteManyAsync(filter);
  118. }
  119. /// <summary>
  120. /// 根据条件获取结果列表
  121. /// </summary>
  122. /// <param name="expression">条件Expression</param>
  123. /// <returns>结果列表</returns>
  124. public Task<List<T>> Find(Expression<Func<T,bool>> expression, ProjectionDefinition<T, T> projecter = null, SortDefinition<T> sorter = null)
  125. {
  126. //Include表示包含那些字段
  127. //ProjectionDefinitionBuilder<VoucherTemplate> project = new ProjectionDefinitionBuilder<VoucherTemplate>();
  128. //var templates = voucherRepository.Find(x => x.AppId == this.AppId, project.Include(x => x.FContentId).
  129. // Include(x => x.TemplateName)).Select(x => new Template { TemplateId = x.FContentId, TemplateName = x.TemplateName }).AsQueryable<Template>();
  130. //Exclude表示包含那些字段
  131. //List<ExchangeRate> exchangeRates = exchangeRateRepository.Find(x => x.AppId == this.AppId, project.Exclude(x => x.CurrencyXRates).Exclude(y => y.ExchangeRateId));
  132. return mongoCollection.Find(expression).Project(projecter).Sort(sorter).ToListAsync();
  133. }
  134. /// <summary>
  135. /// 批处理操作,操作的数据条数需要大于0
  136. /// </summary>
  137. /// <param name="updates"></param>
  138. /// <returns></returns>
  139. public Task<BulkWriteResult<T>> BulkWrite(List<WriteModel<T>> updates, BulkWriteOptions options = null)
  140. {
  141. //eg:使用示例
  142. //List<WriteModel<BusinessDataLockRule>> rules = new List<WriteModel<BusinessDataLockRule>>();
  143. //foreach (var ruleName in ruleNames)
  144. //{
  145. // var lockRule = lockRules.FirstOrDefault(x => x.RuleName == ruleName);
  146. // var dimDLMember = string.Join("-", ruleName.Split("-").Skip(3));
  147. // if (lockRule == null)
  148. // {
  149. // lockRule = new BusinessDataLockRule();
  150. // lockRule.RuleName = ruleName;
  151. // lockRule.Locked = true;
  152. // var insertOneModel = new InsertOneModel<BusinessDataLockRule>(lockRule);
  153. // rules.Add(insertOneModel);
  154. // }
  155. // else
  156. // {
  157. // var filterDefinition = Builders<BusinessDataLockRule>.Filter.Eq(x => x.Id, lockRule.Id);
  158. // var updateDefinition = Builders<BusinessDataLockRule>.Update.Set(x => x.Locked, lockRule.Locked)
  159. // .Set(x => x.LockDimensions, lockRule.LockDimensions)
  160. // .Set(x => x.LockTime, DateTime.Now);
  161. // var updateOneModel = new UpdateOneModel<BusinessDataLockRule>(filterDefinition, updateDefinition);
  162. // rules.Add(updateOneModel);
  163. // }
  164. //}
  165. //if (!rules.IsNullOrEmpty())
  166. //{
  167. // mongoCollection.BulkWriteAsync(rules, new BulkWriteOptions { IsOrdered = false });
  168. //}
  169. return mongoCollection.BulkWriteAsync(updates,options);
  170. }
  171. /// <summary>
  172. /// 根据条件获取结果列表
  173. /// </summary>
  174. /// <param name="filter">条件FilterDefinition</param>
  175. /// <returns>结果列表</returns>
  176. public Task<List<T>> Find(FilterDefinition<T> filter, ProjectionDefinition<T, T> projecter = null, SortDefinition<T> sorter = null)
  177. {
  178. return mongoCollection.Find(filter).Project(projecter).Sort(sorter).ToListAsync();
  179. }
  180. /// <summary>
  181. /// 排序扩展方法
  182. /// </summary>
  183. public static class MongoDBExt
  184. {
  185. //eg:MongoDBExt.GetSortDefinition<CheckRuleGroup>("targetType,targetId,fContentType desc")
  186. /// <summary>
  187. /// 生成SortDefinition对象 根据排序字符串(和sql一样)
  188. /// 规则如下:Model属性名 [asc|desc] ,默认asc可以不写,eg: id,name desc
  189. /// </summary>
  190. /// <typeparam name="T"></typeparam>
  191. /// <param name="orderBy"></param>
  192. /// <returns></returns>
  193. public static SortDefinition<T> GetSortDefinition<T>(string orderBy)
  194. {
  195. if (string.IsNullOrEmpty(orderBy)) return null;
  196. var builder = Builders<T>.Sort;
  197. List<SortDefinition<T>> sorts = new List<SortDefinition<T>>();
  198. foreach (var order in orderBy.Split(','))
  199. {
  200. var ods = order.Split(' ');
  201. if (ods.Length == 1 || (ods.Length == 2 && ods[1].ToLower() == "asc"))
  202. sorts.Add(builder.Ascending(ods[0]));
  203. else
  204. sorts.Add(builder.Descending(ods[0]));
  205. }
  206. return builder.Combine(sorts);
  207. }
  208. }
  209. }
  210. }