您当前的位置: 首页 >  mongodb

天才小熊猫oo

暂无认证

  • 0浏览

    0关注

    37博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Servers.Core库中实现 MongoEntityBase 实现阻塞 异步对MongoDB的增删改查

天才小熊猫oo 发布时间:2022-10-12 22:08:16 ,浏览量:0

        YFMongoDBModelBase类是个模板类,对模板参数进行了约束YFMongoEntityBase,必须要继承YFMongoEntityBase

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;

namespace Servers.Core
{
    // MongoDBModel 基类
    //要继承YFMongoEntityBase
    public abstract class YFMongoDBModelBase
        where T : YFMongoEntityBase, new()
    {
        #region 子类需要实现的属性
        //MongoDB的客户端类(MongoDB是服务器,链接MongoDb的服务器就变成了客户端了)
        protected abstract MongoClient Client
        {
            get;
        }

        //数据库名称
        protected abstract string DatabaseName
        {
            get;
        }

        //集合名称(对应的是Mysql或者是SqlServer中的Table)
        protected abstract string CollectionName
        {
            get;
        }

        //是否记录错误日志(这个一般都要开启的吧?)
        protected virtual bool CanLogError
        {
            get { return false; }
        }
        #endregion


        #region 获取文档集合 GetCollection
        //写了类型之后是会把Mongo中的二进制数据实例化成这个entity类??
        private IMongoCollection m_Collection = null;

        //获取文档集合(get某个类型的Collection,相当于获取某个类型的Table,不过怎么感觉那么奇怪)
        public IMongoCollection GetCollection()
        {
            try
            {
                if (null == m_Collection)
                {
                    IMongoDatabase database = Client.GetDatabase(DatabaseName);
                    m_Collection = database.GetCollection(CollectionName);
                }
                return m_Collection;
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:log类还没写,后面有了log类之后这里的log打印要补上
                }
                else
                {
                    throw e;
                }
                return null;
            }
        }

        #endregion


        #region GetEntity 根据编号查询实体
        //根据编号查询实体
        public T GetEntity(long YFId)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                FilterDefinition filter = Builders.Filter.Eq("YFId", YFId);
                return collection.Find(filter).FirstOrDefault();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:记录错误日志
                }
                else
                {
                    throw e;
                }
                return null;
            }
        }

        //异步根据编号查询实体
        public async Task GetEntityAsync(long YFId)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                FilterDefinition filter = Builders.Filter.Eq("YFId", YFId);
                return await collection.Find(filter).FirstOrDefaultAsync();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:记录错误日志
                }
                else
                {
                    throw e;
                }
                return null;
            }
        }

        //根据条件查询实体
        public T GetEntity(FilterDefinition filter)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                return collection.Find(filter).FirstOrDefault();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
                return null;
            }
        }

        
        //异步根据条件查询实体
        public async Task GetEntityAsync(FilterDefinition filter)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                return await collection.Find(filter).FirstOrDefaultAsync();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
                return null;
            }
        }

        #endregion

        #region 查询数量

        //查询数量(传进去一个规则策略,寻找符合规则的集合数量)
        public long GetCount(FilterDefinition filter)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                return collection.CountDocuments(filter);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else 
                {
                    throw e;
                }
                return 0;
            }
        }

        //异步查询数量
        public async Task GetCountAsync(FilterDefinition filter)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                return await collection.CountDocumentsAsync(filter);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
                return 0;
            }
        }

        #endregion

        #region 根据条件查询数据集合
        /// 
        /// 异步根据条件查询数据集合
        /// 
        /// 过滤条件
        /// 排序
        /// 跳过
        /// 限制数量
        public List GetList(FilterDefinition filter, out long count, string[] field = null, SortDefinition sort = null)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                count = collection.CountDocuments(filter);

                //不指定查询字段???
                if (field == null || field.Length == 0)
                {
                    if (sort == null) 
                        return collection.Find(filter).ToList();
                    
                    //如果有排序规则,进行排序
                    return collection.Find(filter).Sort(sort).ToList();
                }

                //这个的直接翻译叫投影,可以理解成一种投影关系,包含这个名字的(但是不知道include是查找所有的json字符串吗?)
                List fieldList = new List();
                for (int i=0;i< fieldList.Count;++i)
                {
                    fieldList.Add(Builders.Projection.Include(fieldList[i].ToString()));
                }
                ProjectionDefinition projection = Builders.Projection.Combine(fieldList);
                
                //可空类型,不为空就调用Clear
                fieldList?.Clear();

                //没排序规则,就不排序
                if (sort == null)
                    return collection.Find(filter).Project(projection).ToList();
                
                //三重规则??mmp
                return collection.Find(filter).Sort(sort).Project(projection).ToList();
            }
            catch(Exception e) 
            {
                if (CanLogError)
                {
                }
                else 
                {
                    throw e;
                }
                count = 0;
                return null;
            }
        }


        /// 
        /// 异步根据条件查询数据集合
        /// 
        /// 过滤条件
        /// 排序
        /// 跳过
        /// 限制数量
        public async Task GetListAsync(FilterDefinition filter,string[] field = null, SortDefinition sort = null)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                //count = collection.CountDocuments(filter);

                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                        return await collection.Find(filter).ToListAsync();
                    
                    //如果有排序规则,进行排序
                    return await collection.Find(filter).Sort(sort).ToListAsync();
                }

                //这个的直接翻译叫投影,可以理解成一种投影关系,包含这个名字的(但是不知道include是查找所有的json字符串吗?)
                List fieldList = new List();
                for (int i = 0; i < fieldList.Count; ++i)
                {
                    fieldList.Add(Builders.Projection.Include(fieldList[i].ToString()));
                }
                ProjectionDefinition projection = Builders.Projection.Combine(fieldList);

                //可空类型,不为空就调用Clear
                fieldList?.Clear();

                //没排序规则,就不排序
                if (sort == null)
                    return await collection.Find(filter).Project(projection).ToListAsync();

                return await collection.Find(filter).Sort(sort).Project(projection).ToListAsync();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                }
                else
                {
                    throw e;
                }
                //count = 0;
                return null;
            }
        }


        /// 
        /// 查询分页集合
        /// 
        /// 过滤器
        /// 每页数量
        /// 当前页
        /// 总数量
        /// 字段
        /// 排序
        public List GetListByPage(FilterDefinitionfilter,int pageSize,int pageIndex,out long count,string[] field=null,SortDefinitionsort=null)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                count = collection.CountDocuments(filter);

                //不查询指定字段
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                        return collection.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                    
                    //如果有排序规则进行排序
                    collection.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                }

                //制定查询字段
                List fieldList = new List();
                for (int i = 0; i < field.Length; ++i)
                {
                    fieldList.Add(Builders.Projection.Include(field[i].ToString()));    
                }

                ProjectionDefinition projection  =Builders.Projection.Combine(fieldList);
                fieldList?.Clear();
                
                //不排序
                if(sort==null)
                    return collection.Find(filter).Project(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                
                //先投影再排序?这样投影出来的不久不会参与排序了嘛?
                return collection.Find(filter).Sort(sort).Project(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }

                count = 0;
                return null;
            }
        }

        /// 
        /// 异步查询分页集合
        /// 
        /// 过滤器
        /// 每页数量
        /// 当前页
        /// 字段
        /// 排序
        public async Task GetListByPageAsync(FilterDefinition filter, int pageSize, int pageIndex, string[] field = null, SortDefinition sort = null)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                //count = collection.CountDocuments(filter);

                //不查询指定字段
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                        return await collection.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();

                    //如果有排序规则进行排序
                    collection.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                }

                //制定查询字段
                List fieldList = new List();
                for (int i = 0; i < field.Length; ++i)
                {
                    fieldList.Add(Builders.Projection.Include(field[i].ToString()));
                }

                ProjectionDefinition projection = Builders.Projection.Combine(fieldList);
                fieldList?.Clear();

                //不排序
                if (sort == null)
                    return await collection.Find(filter).Project(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();

                return await collection.Find(filter).Sort(sort).Project(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }

                //count = 0;
                return null;
            }
        }
        #endregion

        #region Add添加实体
        //添加实体
        public void Add(T entity)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                collection.InsertOne(entity);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {

                }
                else
                {
                    throw e;
                }
            }
        }

        //异步添加实体
        public async Task AddAsync(T entity)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                await collection.InsertOneAsync(entity);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {

                }
                else
                {
                    throw e;
                }
            }
        }
        #endregion

        #region AddMany 添加多个实体
        //添加多个实体
        public void AddMany(List lst)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                collection.InsertMany(lst);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:   
                }
                else
                {
                    throw e;
                }
            }
        }

        //异步添加多个实体
        public async Task AddManyAsync(List lst)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                await collection.InsertManyAsync(lst);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:   
                }
                else
                {
                    throw e;
                }
            }
        }

        #endregion

        #region Update 修改实体
        //修改实体
        public void Update(T entity)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                FilterDefinition filter = Builders.Filter.Eq("YFId", entity.YFId);
                collection.FindOneAndReplace(filter,entity);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
            }
        }

        //异步修改实体
        public async Task UpdateAsync(T entity)
        {
            try
            {
                IMongoCollection collection = GetCollection();
                FilterDefinition filter = Builders.Filter.Eq("YFId", entity.YFId);
                await collection.FindOneAndReplaceAsync(filter, entity);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
            }
        }
        #endregion


        #region 删除实体
        //删除实体
        public void Delete(long YFId)
        {
            try
            {
                T entity = GetEntity(YFId);
                if (null != entity)
                {
                    entity.Status = DataStatus.Delete;
                    Update(entity);
                }
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
            }
        }

        //异步删除实体
        public async Task DeleteAsync(long YFId)
        {
            try
            {
                T entity = await GetEntityAsync(YFId);
                if (null != entity)
                {
                    entity.Status = DataStatus.Delete;
                    await UpdateAsync(entity);
                }
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
            }
        }
        #endregion

        #region 删除所有文档
        public void DeletaAll()
        {
            try
            {
                //删库跑路了??drop这个table
                IMongoDatabase database = Client.GetDatabase(DatabaseName);
                database.DropCollection(CollectionName);
                //drop了为啥还要再create一下?为了完全覆盖内存吗???
                database.CreateCollection(CollectionName);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO
                }
                else 
                {
                    throw e;
                }
            }
        }
        
        public async Task DeletaAllAsync()
        {
            try
            {
                
                IMongoDatabase database = Client.GetDatabase(DatabaseName);
                await database.DropCollectionAsync(CollectionName);
                await database.CreateCollectionAsync(CollectionName);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO
                }
                else
                {
                    throw e;
                }
            }
        }

        #endregion

    }
}

关注
打赏
1665545649
查看更多评论
立即登录/注册

微信扫码登录

0.0379s