Mongo帮助类(DotNet版本)

该帮助类是针对 C#语言,   我使用的驱动版本为:MongoDB.Driver为2.7.0.0版本;

 增删改查,由网上大佬整理所得;

using Hubert.Common.Method.Log;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Hubert.Common.Method.Mongo
{
    public class MongoDBHelper
    {
        private readonly string connectionString = null;
        private readonly string databaseName = null;
        private IMongoDatabase database = null;
        private readonly bool autoCreateDb = false;
        private readonly bool autoCreateCollection = false;

        static MongoDBHelper()
        {
            BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;
        }

        public MongoDBHelper(string mongoConnStr, string dbName, bool autoCreateDb = false, bool autoCreateCollection = false)
        {
            this.connectionString = mongoConnStr;
            this.databaseName = dbName;
            this.autoCreateDb = autoCreateDb;
            this.autoCreateCollection = autoCreateCollection;
        }

        #region 私有方法

        private MongoClient CreateMongoClient()
        {
            return new MongoClient(connectionString);
        }


        private MongoDB.Driver.IMongoDatabase GetMongoDatabase()
        {
            if (database == null)
            {
                var client = CreateMongoClient();
                if (!DatabaseExists(client, databaseName) && !autoCreateDb)
                {
                    throw new KeyNotFoundException("此MongoDB名称不存在:" + databaseName);
                }

                database = CreateMongoClient().GetDatabase(databaseName);
            }

            return database;
        }

        private bool DatabaseExists(MongoClient client, string dbName)
        {
            try
            {
                var dbNames = client.ListDatabases().ToList().Select(db => db.GetValue("name").AsString);
                return dbNames.Contains(dbName);
            }
            catch //如果连接的账号不能枚举出所有DB会报错,则默认为true
            {
                return true;
            }

        }

        private bool CollectionExists(IMongoDatabase database, string collectionName)
        {
            var options = new ListCollectionsOptions
            {
                Filter = Builders<BsonDocument>.Filter.Eq("name", collectionName)
            };

            return database.ListCollections(options).ToEnumerable().Any();
        }


        private MongoDB.Driver.IMongoCollection<TDoc> GetMongoCollection<TDoc>(string name, MongoCollectionSettings settings = null)
        {
            var mongoDatabase = GetMongoDatabase();

            if (!CollectionExists(mongoDatabase, name) && !autoCreateCollection)
            {
                throw new KeyNotFoundException("此Collection名称不存在:" + name);
            }

            return mongoDatabase.GetCollection<TDoc>(name, settings);
        }

        private List<UpdateDefinition<TDoc>> BuildUpdateDefinition<TDoc>(object doc, string parent)
        {
            var updateList = new List<UpdateDefinition<TDoc>>();
            foreach (var property in typeof(TDoc).GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                var key = parent == null ? property.Name : string.Format("{0}.{1}", parent, property.Name);
                //非空的复杂类型
                if ((property.PropertyType.IsClass || property.PropertyType.IsInterface) && property.PropertyType != typeof(string) && property.GetValue(doc) != null)
                {
                    if (typeof(IList).IsAssignableFrom(property.PropertyType))
                    {
                        #region 集合类型
                        int i = 0;
                        var subObj = property.GetValue(doc);
                        foreach (var item in subObj as IList)
                        {
                            if (item.GetType().IsClass || item.GetType().IsInterface)
                            {
                                updateList.AddRange(BuildUpdateDefinition<TDoc>(doc, string.Format("{0}.{1}", key, i)));
                            }
                            else
                            {
                                updateList.Add(Builders<TDoc>.Update.Set(string.Format("{0}.{1}", key, i), item));
                            }
                            i++;
                        }
                        #endregion
                    }
                    else
                    {
                        #region 实体类型
                        //复杂类型,导航属性,类对象和集合对象 
                        var subObj = property.GetValue(doc);
                        foreach (var sub in property.PropertyType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                        {
                            updateList.Add(Builders<TDoc>.Update.Set(string.Format("{0}.{1}", key, sub.Name), sub.GetValue(subObj)));
                        }
                        #endregion
                    }
                }
                else //简单类型
                {
                    updateList.Add(Builders<TDoc>.Update.Set(key, property.GetValue(doc)));
                }
            }

            return updateList;
        }


        private void CreateIndex<TDoc>(IMongoCollection<TDoc> col, string[] indexFields, CreateIndexOptions options = null)
        {
            if (indexFields == null)
            {
                return;
            }
            var indexKeys = Builders<TDoc>.IndexKeys;
            IndexKeysDefinition<TDoc> keys = null;
            if (indexFields.Length > 0)
            {
                keys = indexKeys.Descending(indexFields[0]);
            }
            for (var i = 1; i < indexFields.Length; i++)
            {
                var strIndex = indexFields[i];
                keys = keys.Descending(strIndex);
            }

            if (keys != null)
            {
                col.Indexes.CreateOne(keys, options);
            }

        }

        #endregion

        public void CreateCollectionIndex<TDoc>(string collectionName, string[] indexFields, CreateIndexOptions options = null)
        {
            CreateIndex(GetMongoCollection<TDoc>(collectionName), indexFields, options);
        }

        public void CreateCollection<TDoc>(string[] indexFields = null, CreateIndexOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            CreateCollection<TDoc>(collectionName, indexFields, options);
        }

        public void CreateCollection<TDoc>(string collectionName, string[] indexFields = null, CreateIndexOptions options = null)
        {
            var mongoDatabase = GetMongoDatabase();
            mongoDatabase.CreateCollection(collectionName);
            CreateIndex(GetMongoCollection<TDoc>(collectionName), indexFields, options);
        }


        public List<TDoc> Find<TDoc>(Expression<Func<TDoc, bool>> filter, FindOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            return Find<TDoc>(collectionName, filter, options);
        }

        public List<TDoc> Find<TDoc>(string collectionName, Expression<Func<TDoc, bool>> filter, FindOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            return colleciton.Find(filter, options).ToList();
        }


        public List<TDoc> FindByPage<TDoc, TResult>(Expression<Func<TDoc, bool>> filter, Expression<Func<TDoc, TResult>> keySelector, int pageIndex, int pageSize, string sort, out int rsCount)
        {
            string collectionName = typeof(TDoc).Name;
            return FindByPage<TDoc, TResult>(collectionName, filter, keySelector, pageIndex, pageSize, sort, out rsCount);
        }

        public List<TDoc> FindByPage<TDoc, TResult>(string collectionName, Expression<Func<TDoc, bool>> filter, Expression<Func<TDoc, TResult>> keySelector, int pageIndex, int pageSize, string sort, out int rsCount)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            rsCount = colleciton.AsQueryable().Where(filter).Count();

            int pageCount = rsCount / pageSize + ((rsCount % pageSize) > 0 ? 1 : 0);
            if (pageIndex > pageCount) pageIndex = pageCount;
            if (pageIndex <= 0) pageIndex = 1;

            List<SortDefinition<TDoc>> sortDefList = new List<SortDefinition<TDoc>>();
            if (sort != null)
            {
                var sortList = sort.Split(',');
                for (var i = 0; i < sortList.Length; i++)
                {
                    var sl = Regex.Replace(sortList[i].Trim(), @"\s+", " ").Split(' ');
                    if (sl.Length == 1 || (sl.Length >= 2 && sl[1].ToLower() == "asc"))
                    {
                        sortDefList.Add(Builders<TDoc>.Sort.Ascending(sl[0]));
                    }
                    else if (sl.Length >= 2 && sl[1].ToLower() == "desc")
                    {
                        sortDefList.Add(Builders<TDoc>.Sort.Descending(sl[0]));
                    }
                }
            }
            var sortDef = Builders<TDoc>.Sort.Combine(sortDefList);
            FindOptions options = null;
            //var result = colleciton.AsQueryable(new AggregateOptions { AllowDiskUse = true }).Where(filter).OrderByDescending(keySelector).Skip((pageIndex - 1) * pageSize).Take(pageSize);

            var result = colleciton.Find(filter, options).Sort(sortDef).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync().Result;
            return result.ToList();
        }

        public void Insert<TDoc>(TDoc doc, InsertOneOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            Insert<TDoc>(collectionName, doc, options);
        }

        public void Insert<TDoc>(string collectionName, TDoc doc, InsertOneOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            colleciton.InsertOne(doc, options);
        }


        public void InsertMany<TDoc>(IEnumerable<TDoc> docs, InsertManyOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            InsertMany<TDoc>(collectionName, docs, options);
        }

        public void InsertMany<TDoc>(string collectionName, IEnumerable<TDoc> docs, InsertManyOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            colleciton.InsertMany(docs, options);
        }

        public void Update<TDoc>(TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc, null);
            colleciton.UpdateOne(filter, Builders<TDoc>.Update.Combine(updateList), options);
        }

        public void Update<TDoc>(string collectionName, TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc, null);
            colleciton.UpdateOne(filter, Builders<TDoc>.Update.Combine(updateList), options);
        }


        public void Update<TDoc>(TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateDefinition<TDoc> updateFields, UpdateOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            Update<TDoc>(collectionName, doc, filter, updateFields, options);
        }

        public void Update<TDoc>(string collectionName, TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateDefinition<TDoc> updateFields, UpdateOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            colleciton.UpdateOne(filter, updateFields, options);
        }


        public void UpdateMany<TDoc>(TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            UpdateMany<TDoc>(collectionName, doc, filter, options);
        }


        public void UpdateMany<TDoc>(string collectionName, TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc, null);
            colleciton.UpdateMany(filter, Builders<TDoc>.Update.Combine(updateList), options);
        }


        public void Delete<TDoc>(Expression<Func<TDoc, bool>> filter, DeleteOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            Delete<TDoc>(collectionName, filter, options);
        }

        public void Delete<TDoc>(string collectionName, Expression<Func<TDoc, bool>> filter, DeleteOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            colleciton.DeleteOne(filter, options);
        }


        public void DeleteMany<TDoc>(Expression<Func<TDoc, bool>> filter, DeleteOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            DeleteMany<TDoc>(collectionName, filter, options);
        }


        public void DeleteMany<TDoc>(string collectionName, Expression<Func<TDoc, bool>> filter, DeleteOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            colleciton.DeleteMany(filter, options);
        }

        public void ClearCollection<TDoc>(string collectionName)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            var inddexs = colleciton.Indexes.List();
            List<IEnumerable<BsonDocument>> docIndexs = new List<IEnumerable<BsonDocument>>();
            while (inddexs.MoveNext())
            {
                docIndexs.Add(inddexs.Current);
            }
            var mongoDatabase = GetMongoDatabase();
            mongoDatabase.DropCollection(collectionName);

            if (!CollectionExists(mongoDatabase, collectionName))
            {
                CreateCollection<TDoc>(collectionName);
            }

            if (docIndexs.Count > 0)
            {
                colleciton = mongoDatabase.GetCollection<TDoc>(collectionName);
                foreach (var index in docIndexs)
                {
                    foreach (IndexKeysDefinition<TDoc> indexItem in index)
                    {
                        try
                        {
                            colleciton.Indexes.CreateOne(indexItem);
                        }
                        catch
                        { }
                    }
                }
            }

        }
        public List<T> Get<T>(string collectionName, Expression<Func<T, bool>> condition, int skip, int limit, string sort)
        {
            return Get(collectionName, new List<Expression<Func<T, bool>>> { condition }, skip, limit, sort);
        }
        public List<TDoc> Get<TDoc>(string collectionName, List<Expression<Func<TDoc, bool>>> conditions, int skip, int limit, string sort)
        {
            if (conditions == null || conditions.Count == 0)
            {
                conditions = new List<Expression<Func<TDoc, bool>>> { x => true };
            }
            var builder = Builders<TDoc>.Filter;
            var filter = builder.And(conditions.Select(x => builder.Where(x)));

            var ret = new List<TDoc>();
            try
            {
                List<SortDefinition<TDoc>> sortDefList = new List<SortDefinition<TDoc>>();
                if (sort != null)
                {
                    var sortList = sort.Split(',');
                    for (var i = 0; i < sortList.Length; i++)
                    {
                        var sl = Regex.Replace(sortList[i].Trim(), @"\s+", " ").Split(' ');
                        if (sl.Length == 1 || (sl.Length >= 2 && sl[1].ToLower() == "asc"))
                        {
                            sortDefList.Add(Builders<TDoc>.Sort.Ascending(sl[0]));
                        }
                        else if (sl.Length >= 2 && sl[1].ToLower() == "desc")
                        {
                            sortDefList.Add(Builders<TDoc>.Sort.Descending(sl[0]));
                        }
                    }
                }
                var mongoDatabase = GetMongoDatabase();
                var colleciton = mongoDatabase.GetCollection<TDoc>(collectionName);

                var sortDef = Builders<TDoc>.Sort.Combine(sortDefList);
                ret = Find(collectionName, filter).Sort(sortDef).Skip(skip).Limit(limit).ToListAsync().Result;
            }
            catch (Exception ex)
            {
                Logger.Error("Get is error", GetType(), ex);
            }
            return ret;
        }
        public IFindFluent<T, T> Find<T>(string collectionName, FilterDefinition<T> filter, FindOptions options = null)
        {
            var mongoDatabase = GetMongoDatabase();
            var colleciton = mongoDatabase.GetCollection<T>(collectionName);

            return colleciton.Find(filter, options);
        }
    }
}

 

 

  希望能对各位朋友有所帮助。

using Hubert.Common.Method.Log;using MongoDB.Bson;using MongoDB.Driver;using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using System.Reflection;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;
namespace Hubert.Common.Method.Mongo{    public class MongoDBHelper    {        private readonly string connectionString = null;        private readonly string databaseName = null;        private IMongoDatabase database = null;        private readonly bool autoCreateDb = false;        private readonly bool autoCreateCollection = false;
        static MongoDBHelper()        {            BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;        }
        public MongoDBHelper(string mongoConnStr, string dbName, bool autoCreateDb = false, bool autoCreateCollection = false)        {            this.connectionString = mongoConnStr;            this.databaseName = dbName;            this.autoCreateDb = autoCreateDb;            this.autoCreateCollection = autoCreateCollection;        }
        #region 私有方法
        private MongoClient CreateMongoClient()        {            return new MongoClient(connectionString);        }

        private MongoDB.Driver.IMongoDatabase GetMongoDatabase()        {            if (database == null)            {                var client = CreateMongoClient();                if (!DatabaseExists(client, databaseName) && !autoCreateDb)                {                    throw new KeyNotFoundException("此MongoDB名称不存在:" + databaseName);                }
                database = CreateMongoClient().GetDatabase(databaseName);            }
            return database;        }
        private bool DatabaseExists(MongoClient client, string dbName)        {            try            {                var dbNames = client.ListDatabases().ToList().Select(db => db.GetValue("name").AsString);                return dbNames.Contains(dbName);            }            catch //如果连接的账号不能枚举出所有DB会报错,则默认为true            {                return true;            }
        }
        private bool CollectionExists(IMongoDatabase database, string collectionName)        {            var options = new ListCollectionsOptions            {                Filter = Builders<BsonDocument>.Filter.Eq("name", collectionName)            };
            return database.ListCollections(options).ToEnumerable().Any();        }

        private MongoDB.Driver.IMongoCollection<TDoc> GetMongoCollection<TDoc>(string name, MongoCollectionSettings settings = null)        {            var mongoDatabase = GetMongoDatabase();
            if (!CollectionExists(mongoDatabase, name) && !autoCreateCollection)            {                throw new KeyNotFoundException("此Collection名称不存在:" + name);            }
            return mongoDatabase.GetCollection<TDoc>(name, settings);        }
        private List<UpdateDefinition<TDoc>> BuildUpdateDefinition<TDoc>(object doc, string parent)        {            var updateList = new List<UpdateDefinition<TDoc>>();            foreach (var property in typeof(TDoc).GetProperties(BindingFlags.Instance | BindingFlags.Public))            {                var key = parent == null ? property.Name : string.Format("{0}.{1}", parent, property.Name);                //非空的复杂类型                if ((property.PropertyType.IsClass || property.PropertyType.IsInterface) && property.PropertyType != typeof(string) && property.GetValue(doc) != null)                {                    if (typeof(IList).IsAssignableFrom(property.PropertyType))                    {                        #region 集合类型                        int i = 0;                        var subObj = property.GetValue(doc);                        foreach (var item in subObj as IList)                        {                            if (item.GetType().IsClass || item.GetType().IsInterface)                            {                                updateList.AddRange(BuildUpdateDefinition<TDoc>(doc, string.Format("{0}.{1}", key, i)));                            }                            else                            {                                updateList.Add(Builders<TDoc>.Update.Set(string.Format("{0}.{1}", key, i), item));                            }                            i++;                        }                        #endregion                    }                    else                    {                        #region 实体类型                        //复杂类型,导航属性,类对象和集合对象                         var subObj = property.GetValue(doc);                        foreach (var sub in property.PropertyType.GetProperties(BindingFlags.Instance | BindingFlags.Public))                        {                            updateList.Add(Builders<TDoc>.Update.Set(string.Format("{0}.{1}", key, sub.Name), sub.GetValue(subObj)));                        }                        #endregion                    }                }                else //简单类型                {                    updateList.Add(Builders<TDoc>.Update.Set(key, property.GetValue(doc)));                }            }
            return updateList;        }

        private void CreateIndex<TDoc>(IMongoCollection<TDoc> col, string[] indexFields, CreateIndexOptions options = null)        {            if (indexFields == null)            {                return;            }            var indexKeys = Builders<TDoc>.IndexKeys;            IndexKeysDefinition<TDoc> keys = null;            if (indexFields.Length > 0)            {                keys = indexKeys.Descending(indexFields[0]);            }            for (var i = 1; i < indexFields.Length; i++)            {                var strIndex = indexFields[i];                keys = keys.Descending(strIndex);            }
            if (keys != null)            {                col.Indexes.CreateOne(keys, options);            }
        }
        #endregion
        public void CreateCollectionIndex<TDoc>(string collectionName, string[] indexFields, CreateIndexOptions options = null)        {            CreateIndex(GetMongoCollection<TDoc>(collectionName), indexFields, options);        }
        public void CreateCollection<TDoc>(string[] indexFields = null, CreateIndexOptions options = null)        {            string collectionName = typeof(TDoc).Name;            CreateCollection<TDoc>(collectionName, indexFields, options);        }
        public void CreateCollection<TDoc>(string collectionName, string[] indexFields = null, CreateIndexOptions options = null)        {            var mongoDatabase = GetMongoDatabase();            mongoDatabase.CreateCollection(collectionName);            CreateIndex(GetMongoCollection<TDoc>(collectionName), indexFields, options);        }

        public List<TDoc> Find<TDoc>(Expression<Func<TDoc, bool>> filter, FindOptions options = null)        {            string collectionName = typeof(TDoc).Name;            return Find<TDoc>(collectionName, filter, options);        }
        public List<TDoc> Find<TDoc>(string collectionName, Expression<Func<TDoc, bool>> filter, FindOptions options = null)        {            var colleciton = GetMongoCollection<TDoc>(collectionName);            return colleciton.Find(filter, options).ToList();        }

        public List<TDoc> FindByPage<TDoc, TResult>(Expression<Func<TDoc, bool>> filter, Expression<Func<TDoc, TResult>> keySelector, int pageIndex, int pageSize, string sort, out int rsCount)        {            string collectionName = typeof(TDoc).Name;            return FindByPage<TDoc, TResult>(collectionName, filter, keySelector, pageIndex, pageSize, sort, out rsCount);        }
        public List<TDoc> FindByPage<TDoc, TResult>(string collectionName, Expression<Func<TDoc, bool>> filter, Expression<Func<TDoc, TResult>> keySelector, int pageIndex, int pageSize, string sort, out int rsCount)        {            var colleciton = GetMongoCollection<TDoc>(collectionName);            rsCount = colleciton.AsQueryable().Where(filter).Count();
            int pageCount = rsCount / pageSize + ((rsCount % pageSize) > 0 ? 1 : 0);            if (pageIndex > pageCount) pageIndex = pageCount;            if (pageIndex <= 0) pageIndex = 1;
            List<SortDefinition<TDoc>> sortDefList = new List<SortDefinition<TDoc>>();            if (sort != null)            {                var sortList = sort.Split(',');                for (var i = 0; i < sortList.Length; i++)                {                    var sl = Regex.Replace(sortList[i].Trim(), @"\s+", " ").Split(' ');                    if (sl.Length == 1 || (sl.Length >= 2 && sl[1].ToLower() == "asc"))                    {                        sortDefList.Add(Builders<TDoc>.Sort.Ascending(sl[0]));                    }                    else if (sl.Length >= 2 && sl[1].ToLower() == "desc")                    {                        sortDefList.Add(Builders<TDoc>.Sort.Descending(sl[0]));                    }                }            }            var sortDef = Builders<TDoc>.Sort.Combine(sortDefList);            FindOptions options = null;            //var result = colleciton.AsQueryable(new AggregateOptions { AllowDiskUse = true }).Where(filter).OrderByDescending(keySelector).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            var result = colleciton.Find(filter, options).Sort(sortDef).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync().Result;            return result.ToList();        }
        public void Insert<TDoc>(TDoc doc, InsertOneOptions options = null)        {            string collectionName = typeof(TDoc).Name;            Insert<TDoc>(collectionName, doc, options);        }
        public void Insert<TDoc>(string collectionName, TDoc doc, InsertOneOptions options = null)        {            var colleciton = GetMongoCollection<TDoc>(collectionName);            colleciton.InsertOne(doc, options);        }

        public void InsertMany<TDoc>(IEnumerable<TDoc> docs, InsertManyOptions options = null)        {            string collectionName = typeof(TDoc).Name;            InsertMany<TDoc>(collectionName, docs, options);        }
        public void InsertMany<TDoc>(string collectionName, IEnumerable<TDoc> docs, InsertManyOptions options = null)        {            var colleciton = GetMongoCollection<TDoc>(collectionName);            colleciton.InsertMany(docs, options);        }
        public void Update<TDoc>(TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null)        {            string collectionName = typeof(TDoc).Name;            var colleciton = GetMongoCollection<TDoc>(collectionName);            List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc, null);            colleciton.UpdateOne(filter, Builders<TDoc>.Update.Combine(updateList), options);        }
        public void Update<TDoc>(string collectionName, TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null)        {            var colleciton = GetMongoCollection<TDoc>(collectionName);            List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc, null);            colleciton.UpdateOne(filter, Builders<TDoc>.Update.Combine(updateList), options);        }

        public void Update<TDoc>(TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateDefinition<TDoc> updateFields, UpdateOptions options = null)        {            string collectionName = typeof(TDoc).Name;            Update<TDoc>(collectionName, doc, filter, updateFields, options);        }
        public void Update<TDoc>(string collectionName, TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateDefinition<TDoc> updateFields, UpdateOptions options = null)        {            var colleciton = GetMongoCollection<TDoc>(collectionName);            colleciton.UpdateOne(filter, updateFields, options);        }

        public void UpdateMany<TDoc>(TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null)        {            string collectionName = typeof(TDoc).Name;            UpdateMany<TDoc>(collectionName, doc, filter, options);        }

        public void UpdateMany<TDoc>(string collectionName, TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null)        {            var colleciton = GetMongoCollection<TDoc>(collectionName);            List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc, null);            colleciton.UpdateMany(filter, Builders<TDoc>.Update.Combine(updateList), options);        }

        public void Delete<TDoc>(Expression<Func<TDoc, bool>> filter, DeleteOptions options = null)        {            string collectionName = typeof(TDoc).Name;            Delete<TDoc>(collectionName, filter, options);        }
        public void Delete<TDoc>(string collectionName, Expression<Func<TDoc, bool>> filter, DeleteOptions options = null)        {            var colleciton = GetMongoCollection<TDoc>(collectionName);            colleciton.DeleteOne(filter, options);        }

        public void DeleteMany<TDoc>(Expression<Func<TDoc, bool>> filter, DeleteOptions options = null)        {            string collectionName = typeof(TDoc).Name;            DeleteMany<TDoc>(collectionName, filter, options);        }

        public void DeleteMany<TDoc>(string collectionName, Expression<Func<TDoc, bool>> filter, DeleteOptions options = null)        {            var colleciton = GetMongoCollection<TDoc>(collectionName);            colleciton.DeleteMany(filter, options);        }
        public void ClearCollection<TDoc>(string collectionName)        {            var colleciton = GetMongoCollection<TDoc>(collectionName);            var inddexs = colleciton.Indexes.List();            List<IEnumerable<BsonDocument>> docIndexs = new List<IEnumerable<BsonDocument>>();            while (inddexs.MoveNext())            {                docIndexs.Add(inddexs.Current);            }            var mongoDatabase = GetMongoDatabase();            mongoDatabase.DropCollection(collectionName);
            if (!CollectionExists(mongoDatabase, collectionName))            {                CreateCollection<TDoc>(collectionName);            }
            if (docIndexs.Count > 0)            {                colleciton = mongoDatabase.GetCollection<TDoc>(collectionName);                foreach (var index in docIndexs)                {                    foreach (IndexKeysDefinition<TDoc> indexItem in index)                    {                        try                        {                            colleciton.Indexes.CreateOne(indexItem);                        }                        catch                        { }                    }                }            }
        }        public List<T> Get<T>(string collectionName, Expression<Func<T, bool>> condition, int skip, int limit, string sort)        {            return Get(collectionName, new List<Expression<Func<T, bool>>> { condition }, skip, limit, sort);        }        public List<TDoc> Get<TDoc>(string collectionName, List<Expression<Func<TDoc, bool>>> conditions, int skip, int limit, string sort)        {            if (conditions == null || conditions.Count == 0)            {                conditions = new List<Expression<Func<TDoc, bool>>> { x => true };            }            var builder = Builders<TDoc>.Filter;            var filter = builder.And(conditions.Select(x => builder.Where(x)));
            var ret = new List<TDoc>();            try            {                List<SortDefinition<TDoc>> sortDefList = new List<SortDefinition<TDoc>>();                if (sort != null)                {                    var sortList = sort.Split(',');                    for (var i = 0; i < sortList.Length; i++)                    {                        var sl = Regex.Replace(sortList[i].Trim(), @"\s+", " ").Split(' ');                        if (sl.Length == 1 || (sl.Length >= 2 && sl[1].ToLower() == "asc"))                        {                            sortDefList.Add(Builders<TDoc>.Sort.Ascending(sl[0]));                        }                        else if (sl.Length >= 2 && sl[1].ToLower() == "desc")                        {                            sortDefList.Add(Builders<TDoc>.Sort.Descending(sl[0]));                        }                    }                }                var mongoDatabase = GetMongoDatabase();                var colleciton = mongoDatabase.GetCollection<TDoc>(collectionName);
                var sortDef = Builders<TDoc>.Sort.Combine(sortDefList);                ret = Find(collectionName, filter).Sort(sortDef).Skip(skip).Limit(limit).ToListAsync().Result;            }            catch (Exception ex)            {                Logger.Error("Get is error", GetType(), ex);            }            return ret;        }        public IFindFluent<T, T> Find<T>(string collectionName, FilterDefinition<T> filter, FindOptions options = null)        {            var mongoDatabase = GetMongoDatabase();            var colleciton = mongoDatabase.GetCollection<T>(collectionName);
            return colleciton.Find(filter, options);        }    }}

 

转载于:https://www.cnblogs.com/HubertBiyo/p/9285225.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,下面是实现 MongoDB 操作的类的一个示例: ``` import pymongo class MongoOperator: def __init__(self, host, port, username, password, db_name): """ 初始化连接信息 """ self.host = host self.port = port self.username = username self.password = password self.db_name = db_name self.client = None self.db = None def connect(self): """ 连接到 MongoDB 服务器 """ self.client = pymongo.MongoClient(self.host, self.port) self.db = self.client[self.db_name] # 如果设置了用户名和密码,则需要进行身份认证 if self.username and self.password: self.db.authenticate(self.username, self.password) def close(self): """ 关闭与 MongoDB 服务器的连接 """ self.client.close() def insert_one(self, collection_name, doc): """ 向集合中插入一条文档 """ collection = self.db[collection_name] result = collection.insert_one(doc) return result.inserted_id def insert_many(self, collection_name, docs): """ 向集合中插入多条文档 """ collection = self.db[collection_name] result = collection.insert_many(docs) return result.inserted_ids def find_one(self, collection_name, filter, projection=None): """ 从集合中查询一条文档 """ collection = self.db[collection_name] if projection: return collection.find_one(filter, projection) else: return collection.find_one(filter) def find(self, collection_name, filter, projection=None): """ 从集合中查询多条文档 """ collection = self.db[collection_name] if projection: return collection.find(filter, projection) else: return collection.find(filter) def update_one(self, collection_name, filter, update): """ 更新集合中的一条文档 """ collection = self.db[collection_name] result = collection.update_one(filter, update) ### 回答2: 实现一个Mongo操作类可以辅助我们更方便地对MongoDB进行数据操作。首先,我们需要引入MongoDB官方提供的mongoDB Driver for Node.js。然后,我们可以定义一个Mongo类,该类包含连接MongoDB并操作数据的一些方法。 ``` const { MongoClient } = require('mongodb'); class Mongo { constructor(url, dbName) { this.url = url; this.dbName = dbName; this.client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true }); this.db = null; } async connect() { try { await this.client.connect(); this.db = this.client.db(this.dbName); console.log('Connected to MongoDB successfully'); } catch (error) { console.error('Failed to connect to MongoDB', error); } } async insertOne(collectionName, document) { try { await this.db.collection(collectionName).insertOne(document); console.log('Document inserted successfully'); } catch (error) { console.error('Failed to insert document', error); } } async findOne(collectionName, query) { try { const result = await this.db.collection(collectionName).findOne(query); console.log('Found document:', result); return result; } catch (error) { console.error('Failed to find document', error); return null; } } // 其他操作方法,如updateOne、deleteOne等等可以类似地实现 async disconnect() { try { await this.client.close(); console.log('Disconnected from MongoDB'); } catch (error) { console.error('Failed to close MongoDB connection', error); } } } module.exports = Mongo; ``` 以上是一个简单的Mongo操作类的实现,通过这个类我们可以连接MongoDB数据库、插入文档、查询文档等操作。我们在构造函数中传入MongoDB的URL和数据库名称,然后可以调用`connect()`方法来连接数据库,操作完数据后可以调用`disconnect()`方法来断开数据库连接。 ### 回答3: 实现一个 MONGO 操作类可以通过以下步骤进行: 首先,需要引入 MongoDB 官方提供的驱动程序,可以使用 Pymongo。在 Python 中使用 Pymongo 操作 MongoDB 数据库非常方便。 然后,可以创建一个 MONGO 操作类,该类可以包含以下方法: 1. 连接数据库方法:可以在该方法中使用 Pymongo 提供的 MongoClient 连接到 MongoDB 数据库。可以传入连接参数,如数据库的 IP 地址和端口号。 2. 选择数据库方法:可以在该方法中选择要操作的数据库。可以利用连接数据库方法返回的 MongoClient 对象的属性来选择数据库。 3. 选择集合方法:可以在该方法中选择要操作的集合。可以使用 MongoClient 对象的属性选择集合。 4. 插入文档方法:可以在该方法中插入文档到指定的集合中。可以使用集合对象的 insert_one 或 insert_many 方法来插入文档。 5. 查询文档方法:可以在该方法中查询指定条件的文档。可以使用集合对象的 find 方法来查询文档。 6. 更新文档方法:可以在该方法中更新符合条件的文档。可以使用集合对象的 update_one 或 update_many 方法来更新文档。 7. 删除文档方法:可以在该方法中删除符合条件的文档。可以使用集合对象的 delete_one 或 delete_many 方法来删除文档。 8. 断开数据库方法:可以在该方法中断开与 MongoDB 数据库的连接。可以使用 MongoClient 对象的 close 方法来断开连接。 通过以上步骤,就可以实现一个 MONGO 操作类,该类可以用于连接、选择数据库、选择集合、插入文档、查询文档、更新文档和删除文档等操作。利用该类,可以更加方便地对 MongoDB 数据库进行操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值