| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226 |
- using Amazon.Runtime.Internal;
- using Business.Core.Attributes;
- using Microsoft.Extensions.Options;
- using MongoDB.Bson;
- using MongoDB.Bson.Serialization.Attributes;
- using MongoDB.Driver;
- using MongoDB.Driver.Linq;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- using Volo.Abp.Domain.Entities;
- using Volo.Abp.Domain.Repositories;
- namespace Business.Core.MongoDBHelper
- {
- /// <summary>
- /// MongoDB帮助类
- /// </summary>
- public class MongoDBTools<T> : IMongoDB<T>
- {
- public readonly IMongoCollection<T> mongoCollection;
- public readonly IMongoDatabase dataBase;
- public IOptionsSnapshot<Config> _config;
- public CollectionNameAttribute collectonName;
- /// <summary>
- /// MongoDB链接
- /// </summary>
- /// <param name="config"></param>
- /// <exception cref="NotImplementedException"></exception>
- public MongoDBTools(IOptionsSnapshot<Config> config)
- {
- _config = config;
-
- collectonName = typeof(T).GetCustomAttributes(typeof(CollectionNameAttribute), true).FirstOrDefault() as CollectionNameAttribute;
- if (collectonName == null)
- {
- throw new NotImplementedException("请配置Attribute属性!");
- }
- //数据库链接
- MongoClient client = new MongoClient(config.Value.connectstring + collectonName.DatabaseName);
- //数据库
- dataBase = client.GetDatabase(collectonName.DatabaseName);
- //表名
- mongoCollection = dataBase.GetCollection<T>(collectonName.CollectionName);
- }
- /// <summary>
- /// 插入一条数据
- /// </summary>
- /// <param name="document"></param>
- /// <returns></returns>
- public Task InsertOne(T document)
- {
- return mongoCollection.InsertOneAsync(document);
- }
- /// <summary>
- /// 插入多条数据
- /// </summary>
- /// <param name="documents"></param>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- public Task InsertMany(List<T> documents)
- {
- return mongoCollection.InsertManyAsync(documents,new InsertManyOptions() { IsOrdered = false});
- }
- /// <summary>
- /// 获取所有数据
- /// </summary>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- public Task<List<T>> GetAll()
- {
- return mongoCollection.AsQueryable<T>().ToListAsync();
- }
- /// <summary>
- /// 根据条件获取数据
- /// </summary>
- /// <returns></returns>
- public Task<List<T>> GetManyByCondition(Expression<Func<T, bool>> filter)
- {
- return mongoCollection.Find(filter).ToListAsync();
- }
- /// <summary>
- /// 根据条件获取数据
- /// </summary>
- /// <returns></returns>
- public Task<List<T>> GetManyByIds(FilterDefinition<T> filter)
- {
- return mongoCollection.Find(filter).ToListAsync();
- }
- /// <summary>
- /// 删除数据
- /// </summary>
- /// <param name="expression"></param>
- /// <param name="isOne"></param>
- /// <returns></returns>
- public Task<DeleteResult> Delete(Expression<Func<T, bool>> expression, bool isOne = false)
- {
- if (isOne)
- return mongoCollection.DeleteOneAsync(expression);
- else
- return mongoCollection.DeleteManyAsync(expression);
- }
- /// <summary>
- /// 删除数据
- /// </summary>
- /// <param name="filter"></param>
- /// <param name="isOne"></param>
- /// <returns></returns>
- public Task<DeleteResult> Delete(FilterDefinition<T> filter, bool isOne = false)
- {
- if (isOne)
- return mongoCollection.DeleteOneAsync(filter);
- else
- return mongoCollection.DeleteManyAsync(filter);
- }
- /// <summary>
- /// 根据条件获取结果列表
- /// </summary>
- /// <param name="expression">条件Expression</param>
- /// <returns>结果列表</returns>
- public Task<List<T>> Find(Expression<Func<T,bool>> expression, ProjectionDefinition<T, T> projecter = null, SortDefinition<T> sorter = null)
- {
- //Include表示包含那些字段
- //ProjectionDefinitionBuilder<VoucherTemplate> project = new ProjectionDefinitionBuilder<VoucherTemplate>();
- //var templates = voucherRepository.Find(x => x.AppId == this.AppId, project.Include(x => x.FContentId).
- // Include(x => x.TemplateName)).Select(x => new Template { TemplateId = x.FContentId, TemplateName = x.TemplateName }).AsQueryable<Template>();
- //Exclude表示包含那些字段
- //List<ExchangeRate> exchangeRates = exchangeRateRepository.Find(x => x.AppId == this.AppId, project.Exclude(x => x.CurrencyXRates).Exclude(y => y.ExchangeRateId));
- return mongoCollection.Find(expression).Project(projecter).Sort(sorter).ToListAsync();
- }
- /// <summary>
- /// 批处理操作,操作的数据条数需要大于0
- /// </summary>
- /// <param name="updates"></param>
- /// <returns></returns>
- public Task<BulkWriteResult<T>> BulkWrite(List<WriteModel<T>> updates, BulkWriteOptions options = null)
- {
- //eg:使用示例
- //List<WriteModel<BusinessDataLockRule>> rules = new List<WriteModel<BusinessDataLockRule>>();
- //foreach (var ruleName in ruleNames)
- //{
- // var lockRule = lockRules.FirstOrDefault(x => x.RuleName == ruleName);
- // var dimDLMember = string.Join("-", ruleName.Split("-").Skip(3));
- // if (lockRule == null)
- // {
- // lockRule = new BusinessDataLockRule();
- // lockRule.RuleName = ruleName;
- // lockRule.Locked = true;
- // var insertOneModel = new InsertOneModel<BusinessDataLockRule>(lockRule);
- // rules.Add(insertOneModel);
- // }
- // else
- // {
- // var filterDefinition = Builders<BusinessDataLockRule>.Filter.Eq(x => x.Id, lockRule.Id);
- // var updateDefinition = Builders<BusinessDataLockRule>.Update.Set(x => x.Locked, lockRule.Locked)
- // .Set(x => x.LockDimensions, lockRule.LockDimensions)
- // .Set(x => x.LockTime, DateTime.Now);
- // var updateOneModel = new UpdateOneModel<BusinessDataLockRule>(filterDefinition, updateDefinition);
- // rules.Add(updateOneModel);
- // }
- //}
- //if (!rules.IsNullOrEmpty())
- //{
- // mongoCollection.BulkWriteAsync(rules, new BulkWriteOptions { IsOrdered = false });
- //}
- return mongoCollection.BulkWriteAsync(updates,options);
- }
- /// <summary>
- /// 根据条件获取结果列表
- /// </summary>
- /// <param name="filter">条件FilterDefinition</param>
- /// <returns>结果列表</returns>
- public Task<List<T>> Find(FilterDefinition<T> filter, ProjectionDefinition<T, T> projecter = null, SortDefinition<T> sorter = null)
- {
- return mongoCollection.Find(filter).Project(projecter).Sort(sorter).ToListAsync();
- }
- /// <summary>
- /// 排序扩展方法
- /// </summary>
- public static class MongoDBExt
- {
- //eg:MongoDBExt.GetSortDefinition<CheckRuleGroup>("targetType,targetId,fContentType desc")
- /// <summary>
- /// 生成SortDefinition对象 根据排序字符串(和sql一样)
- /// 规则如下:Model属性名 [asc|desc] ,默认asc可以不写,eg: id,name desc
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="orderBy"></param>
- /// <returns></returns>
- public static SortDefinition<T> GetSortDefinition<T>(string orderBy)
- {
- if (string.IsNullOrEmpty(orderBy)) return null;
- var builder = Builders<T>.Sort;
- List<SortDefinition<T>> sorts = new List<SortDefinition<T>>();
- foreach (var order in orderBy.Split(','))
- {
- var ods = order.Split(' ');
- if (ods.Length == 1 || (ods.Length == 2 && ods[1].ToLower() == "asc"))
- sorts.Add(builder.Ascending(ods[0]));
- else
- sorts.Add(builder.Descending(ods[0]));
- }
- return builder.Combine(sorts);
- }
- }
- }
- }
|