MongoDBTools.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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> where T : Entity<long>
  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. //数据库链接
  38. MongoClient client = new MongoClient(config.Value.connectstring);
  39. collectonName = typeof(T).GetCustomAttributes(typeof(CollectionNameAttribute), true).FirstOrDefault() as CollectionNameAttribute;
  40. if (collectonName == null)
  41. {
  42. throw new NotImplementedException("请配置Attribute属性!");
  43. }
  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. /// <param name="documents"></param>
  72. /// <param name="id"></param>
  73. /// <returns></returns>
  74. public Task<ReplaceOneResult> UpdateOne(T documents,long id)
  75. {
  76. return mongoCollection.ReplaceOneAsync(Builders<T>.Filter.Eq(p=>p.Id, id), documents);
  77. }
  78. /// <summary>
  79. /// 获取所有数据
  80. /// </summary>
  81. /// <returns></returns>
  82. /// <exception cref="NotImplementedException"></exception>
  83. public Task<List<T>> GetAll()
  84. {
  85. return mongoCollection.AsQueryable<T>().ToListAsync();
  86. }
  87. /// <summary>
  88. /// 跟据Id获取数据
  89. /// </summary>
  90. /// <param name="id"></param>
  91. /// <returns></returns>
  92. /// <exception cref="NotImplementedException"></exception>
  93. public Task<T> GetOneByID(long id)
  94. {
  95. return mongoCollection.Find(p => p.Id == id).FirstOrDefaultAsync();
  96. }
  97. /// <summary>
  98. /// 根据条件获取数据
  99. /// </summary>
  100. /// <returns></returns>
  101. public Task<List<T>> GetManyByCondition(Expression<Func<T, bool>> filter)
  102. {
  103. return mongoCollection.Find(filter).ToListAsync();
  104. }
  105. /// <summary>
  106. /// 根据条件获取数据
  107. /// </summary>
  108. /// <returns></returns>
  109. public Task<List<T>> GetManyByIds(FilterDefinition<T> filter)
  110. {
  111. return mongoCollection.Find(filter).ToListAsync();
  112. }
  113. /// <summary>
  114. /// 根据id删除对象
  115. /// </summary>
  116. /// <param name="id"></param>
  117. public Task DeleteById(long id)
  118. {
  119. return mongoCollection.DeleteManyAsync(s => id==s.Id);
  120. }
  121. /// <summary>
  122. /// 根据id列表批量删除对象
  123. /// </summary>
  124. /// <param name="ids">id列表</param>
  125. public Task DeleteByIds(IEnumerable<long> ids)
  126. {
  127. return mongoCollection.DeleteManyAsync(s => ids.Contains(s.Id));
  128. }
  129. /// <summary>
  130. /// 删除数据
  131. /// </summary>
  132. /// <param name="expression"></param>
  133. /// <param name="isOne"></param>
  134. /// <returns></returns>
  135. public Task<DeleteResult> Delete(Expression<Func<T, bool>> expression, bool isOne = false)
  136. {
  137. if (isOne)
  138. return mongoCollection.DeleteOneAsync(expression);
  139. else
  140. return mongoCollection.DeleteManyAsync(expression);
  141. }
  142. /// <summary>
  143. /// 删除数据
  144. /// </summary>
  145. /// <param name="filter"></param>
  146. /// <param name="isOne"></param>
  147. /// <returns></returns>
  148. public Task<DeleteResult> Delete(FilterDefinition<T> filter, bool isOne = false)
  149. {
  150. if (isOne)
  151. return mongoCollection.DeleteOneAsync(filter);
  152. else
  153. return mongoCollection.DeleteManyAsync(filter);
  154. }
  155. /// <summary>
  156. /// 根据条件获取结果列表
  157. /// </summary>
  158. /// <param name="expression">条件Expression</param>
  159. /// <returns>结果列表</returns>
  160. public Task<List<T>> Find(Expression<Func<T,bool>> expression, ProjectionDefinition<T, T> projecter = null, SortDefinition<T> sorter = null)
  161. {
  162. //Include表示包含那些字段
  163. //ProjectionDefinitionBuilder<VoucherTemplate> project = new ProjectionDefinitionBuilder<VoucherTemplate>();
  164. //var templates = voucherRepository.Find(x => x.AppId == this.AppId, project.Include(x => x.FContentId).
  165. // Include(x => x.TemplateName)).Select(x => new Template { TemplateId = x.FContentId, TemplateName = x.TemplateName }).AsQueryable<Template>();
  166. //Exclude表示包含那些字段
  167. //List<ExchangeRate> exchangeRates = exchangeRateRepository.Find(x => x.AppId == this.AppId, project.Exclude(x => x.CurrencyXRates).Exclude(y => y.ExchangeRateId));
  168. return mongoCollection.Find(expression).Project(projecter).Sort(sorter).ToListAsync();
  169. }
  170. /// <summary>
  171. /// 批处理操作,操作的数据条数需要大于0
  172. /// </summary>
  173. /// <param name="updates"></param>
  174. /// <returns></returns>
  175. public Task<BulkWriteResult<T>> BulkWrite(List<WriteModel<T>> updates, BulkWriteOptions options = null)
  176. {
  177. //eg:使用示例
  178. //List<WriteModel<BusinessDataLockRule>> rules = new List<WriteModel<BusinessDataLockRule>>();
  179. //foreach (var ruleName in ruleNames)
  180. //{
  181. // var lockRule = lockRules.FirstOrDefault(x => x.RuleName == ruleName);
  182. // var dimDLMember = string.Join("-", ruleName.Split("-").Skip(3));
  183. // if (lockRule == null)
  184. // {
  185. // lockRule = new BusinessDataLockRule();
  186. // lockRule.RuleName = ruleName;
  187. // lockRule.Locked = true;
  188. // var insertOneModel = new InsertOneModel<BusinessDataLockRule>(lockRule);
  189. // rules.Add(insertOneModel);
  190. // }
  191. // else
  192. // {
  193. // var filterDefinition = Builders<BusinessDataLockRule>.Filter.Eq(x => x.Id, lockRule.Id);
  194. // var updateDefinition = Builders<BusinessDataLockRule>.Update.Set(x => x.Locked, lockRule.Locked)
  195. // .Set(x => x.LockDimensions, lockRule.LockDimensions)
  196. // .Set(x => x.LockTime, DateTime.Now);
  197. // var updateOneModel = new UpdateOneModel<BusinessDataLockRule>(filterDefinition, updateDefinition);
  198. // rules.Add(updateOneModel);
  199. // }
  200. //}
  201. //if (!rules.IsNullOrEmpty())
  202. //{
  203. // mongoCollection.BulkWriteAsync(rules, new BulkWriteOptions { IsOrdered = false });
  204. //}
  205. return mongoCollection.BulkWriteAsync(updates,options);
  206. }
  207. /// <summary>
  208. /// 排序扩展方法
  209. /// </summary>
  210. public static class MongoDBExt
  211. {
  212. //eg:MongoDBExt.GetSortDefinition<CheckRuleGroup>("targetType,targetId,fContentType desc")
  213. /// <summary>
  214. /// 生成SortDefinition对象 根据排序字符串(和sql一样)
  215. /// 规则如下:Model属性名 [asc|desc] ,默认asc可以不写,eg: id,name desc
  216. /// </summary>
  217. /// <typeparam name="T"></typeparam>
  218. /// <param name="orderBy"></param>
  219. /// <returns></returns>
  220. public static SortDefinition<T> GetSortDefinition<T>(string orderBy)
  221. {
  222. if (string.IsNullOrEmpty(orderBy)) return null;
  223. var builder = Builders<T>.Sort;
  224. List<SortDefinition<T>> sorts = new List<SortDefinition<T>>();
  225. foreach (var order in orderBy.Split(','))
  226. {
  227. var ods = order.Split(' ');
  228. if (ods.Length == 1 || (ods.Length == 2 && ods[1].ToLower() == "asc"))
  229. sorts.Add(builder.Ascending(ods[0]));
  230. else
  231. sorts.Add(builder.Descending(ods[0]));
  232. }
  233. return builder.Combine(sorts);
  234. }
  235. }
  236. /// <summary>
  237. /// 删除数据-直接删除集合,慎用,慎用,慎用
  238. /// </summary>
  239. /// <returns></returns>
  240. public Task DeleteAll()
  241. {
  242. return dataBase.DropCollectionAsync(collectonName.CollectionName);
  243. }
  244. }
  245. }