123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512 |
- using CZFW.Core;
- using CZFW.Framework.Model;
- using CZFW.Framework.Model.ViewModel;
- using MongoDB.Bson;
- using MongoDB.Driver;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace CZFW.MDB
- {
- public class MongoRepository : IMongoRepository
- {
- public MongoRepository()
- {
- }
- public MongoRepository(string tableName)
- {
- currentTableName = tableName;
- }
- private IMongoDatabase server;
- public IMongoDatabase Database
- {
- get
- {
- if (server is null)
- {
- var conStr = ConfigHelper.GetValue<string>("ConnectionStrings:MongoConnection");
- var client = new MongoClient(conStr);
- var dbName = ConfigHelper.GetValue<string>("ConnectionStrings:DbName");
- server = client.GetDatabase(dbName);
- }
- return server;
- }
- set { server = value; }
- }
- private string currentTableName;
- public string CurrentTableName
- {
- get
- {
- if (string.IsNullOrWhiteSpace(currentTableName))
- throw new Exception("尚未指定当前操作集合名称!");
- return currentTableName;
- }
- set { currentTableName = value; }
- }
- private IMongoCollection<BsonDocument> currentTable;
- public IMongoCollection<BsonDocument> CurrentTable
- {
- get
- {
- if (currentTable == null)
- currentTable = Database.GetCollection<BsonDocument>(CurrentTableName);
- return currentTable;
- }
- set
- {
- currentTable = value;
- }
- }
- public Task<ResultModel> CopyTableAsync(string srcTableName, string destTableName, bool copyData = false)
- {
- throw new NotImplementedException();
- }
- public async Task<ResultModel> CreateTableAsync(string tableName, CreateCollectionOptions options = null)
- {
- try
- {
- await Database.CreateCollectionAsync(tableName, options);
- return new ResultModel();
- }
- catch (Exception err)
- {
- return new ResultModel($"创建失败,错误信息:{err}");
- }
- }
- public async Task<long> GetCountAsync(string query = null)
- {
- if (string.IsNullOrWhiteSpace(query))
- query = "{}";
- var filter = BsonDocument.Parse(query);
- var res = await CurrentTable.CountAsync(filter);
- return res;
- }
- public async Task<dynamic> GetOneAsync(string query)
- {
- var filter = BsonDocument.Parse(query);
- var res = await CurrentTable.FindAsync(filter);
- dynamic tp = res.FirstOrDefault();
- return tp;
- }
- public async Task<dynamic> GetAsync(string key)
- {
- var filter = new BsonDocument("_id", new ObjectId(key));
- var res = await CurrentTable.FindAsync(filter);
- dynamic tp = res.FirstOrDefault();
- return tp;
- }
- public async Task<(dynamic data, PagerModel pager)> GetListAsync(string query = "{}", string sort = null, string projection = null, int pageIndex = 1, int pageSize = 20)
- {
- var filter = BsonDocument.Parse(query);
- SortDefinition<BsonDocument> sortDef = string.IsNullOrWhiteSpace(sort) ? BsonDocument.Parse(sort) : null;
- ProjectionDefinition<BsonDocument> projectionDef = string.IsNullOrWhiteSpace(projection) ? BsonDocument.Parse(projection) : null;
- var option = new FindOptions<BsonDocument, BsonDocument>();
- long count = CurrentTable.Count(filter);
- PagerModel pager = null;
- if (pageIndex > 0)
- {
- option.Limit = pageIndex;
- option.Skip = (pageIndex - 1) * pageSize;
- pager = new PagerModel((int)count, pageIndex, pageSize);
- }
- option.Sort = sortDef;
- option.Projection = projectionDef;
- var res = await CurrentTable.FindAsync(filter, option);
- dynamic tp = res.ToList();
- return (tp, pager);
- }
- public async Task<ResultModel> RemoveAsync(string key)
- {
- FilterDefinition<BsonDocument> filter = new BsonDocument("_id", new ObjectId(key));
- var tp = await CurrentTable.DeleteOneAsync(filter);
- var res = new ResultModel
- {
- Success = tp.DeletedCount > 0,
- AffectedRows = (int)tp.DeletedCount
- };
- return res;
- }
- public async Task<ResultModel> RemoveManyAsync(string query)
- {
- FilterDefinition<BsonDocument> filter = BsonDocument.Parse(query);
- var tp = await CurrentTable.DeleteManyAsync(filter);
- var res = new ResultModel
- {
- Success = tp.DeletedCount > 0,
- AffectedRows = (int)tp.DeletedCount
- };
- return res;
- }
- public async Task<ResultModel> RemoveTableAsync(string tableName)
- {
- try
- {
- await Database.DropCollectionAsync(tableName);
- return new ResultModel();
- }
- catch (Exception err)
- {
- return new ResultModel($"删除表失败,错误信息:{err.Message}");
- }
- }
- //public async Task<ResultModel> RunCommandAsync(string command)
- //{
- // throw new NotImplementedException();
- //}
- public async Task<ResultModel> UpdateAsync(string key, string set, string arrayFilter = null)
- {
- var filter = new BsonDocument("_id", new ObjectId(key));
- var setDef = BsonDocument.Parse(set);
- UpdateOptions updateOptions = null;
- if (!string.IsNullOrWhiteSpace(arrayFilter))
- {
- var doc = BsonDocument.Parse(arrayFilter);
- var arrayFilterDefinition = new BsonDocumentArrayFilterDefinition<BsonDocument>(doc);
- updateOptions = new UpdateOptions
- {
- ArrayFilters = new List<ArrayFilterDefinition> { arrayFilterDefinition }
- };
- }
- try
- {
- var tp = await CurrentTable.UpdateOneAsync(filter, setDef, updateOptions);
- return new ResultModel
- {
- AffectedRows = (int)tp.ModifiedCount,
- Success = tp.ModifiedCount > 0,
- };
- }
- catch (Exception err)
- {
- return new ResultModel($"更新失败,错误信息:{err.Message}");
- }
- }
- public async Task<ResultModel> UpdateManyAsync(string query, string set, string arrayFilter = null)
- {
- var filter = BsonDocument.Parse(query);
- var setDef = BsonDocument.Parse(set);
- UpdateOptions updateOptions = null;
- if (!string.IsNullOrWhiteSpace(arrayFilter))
- {
- var doc = BsonDocument.Parse(arrayFilter);
- var arrayFilterDefinition = new BsonDocumentArrayFilterDefinition<BsonDocument>(doc);
- updateOptions = new UpdateOptions
- {
- ArrayFilters = new List<ArrayFilterDefinition> { arrayFilterDefinition }
- };
- }
- try
- {
- var tp = await CurrentTable.UpdateManyAsync(filter, setDef, updateOptions);
- return new ResultModel
- {
- AffectedRows = (int)tp.ModifiedCount,
- Success = tp.ModifiedCount > 0
- };
- }
- catch (Exception err)
- {
- return new ResultModel($"更新失败,错误信息:{err.Message}");
- }
- }
-
- public void SetCurrentTable(string tableName)
- {
- if(currentTableName!=tableName)
- {
- currentTableName = tableName;
- currentTable = null;
- }
- }
- public IMongoCollection<BsonDocument> GetTable(string tableName)
- {
- var table = Database.GetCollection<BsonDocument>(tableName);
- return table;
- }
- public BsonDocument Get(string key, string projection="{}")
- {
- var filter = new BsonDocument("_id", new ObjectId(key));
- var res = CurrentTable.Find(filter).Project(projection).FirstOrDefault();
- return res;
- }
- public BsonDocument GetOne(string query = "{}", string projection = "{}", string sort="{}")
- {
- var filter = BsonDocument.Parse(query);
- var res = CurrentTable.Find(filter).Project(projection).Sort(sort).FirstOrDefault();
- return res;
- }
- public BsonArray GetList(string query ="{}", string projection="{}", int pageIndex=1,int pageSize=20, string sort="{}", bool useCursor=false)
- {
- var filter = BsonDocument.Parse(query);
- var projectionDef = BsonDocument.Parse(projection);
- var find = CurrentTable.Find(filter).Project<BsonDocument>(projectionDef).Sort(sort).Skip((pageIndex-1)*pageSize).Limit(pageSize);
- if (!useCursor)
- return new BsonArray(find.ToList());
- var bsonarray = new BsonArray();
- foreach (var item in find.ToEnumerable())
- {
- bsonarray.Add(item);
- }
- return bsonarray;
- }
- public long GetCount(string query = null)
- {
- if (string.IsNullOrWhiteSpace(query))
- query = "{}";
- var filter = BsonDocument.Parse(query);
- var res = CurrentTable.Count(filter);
- return res;
- }
- public ResultModel CreateTable(string tableName, CreateCollectionOptions options = null)
- {
- try
- {
- Database.CreateCollection(tableName, options);
- return new ResultModel();
- }
- catch (Exception err)
- {
- return new ResultModel($"创建失败,错误信息:{err}");
- }
- }
- public ResultModel RemoveTable(string tableName)
- {
- try
- {
- Database.DropCollection(tableName);
- return new ResultModel();
- }
- catch (Exception err)
- {
- return new ResultModel($"删除表失败,错误信息:{err.Message}");
- }
- }
- public ResultModel CopyTable(string srcTableName, string destTableName, bool copyData = false)
- {
- throw new NotImplementedException();
- }
- public ResultModel Remove(string key)
- {
- FilterDefinition<BsonDocument> filter = new BsonDocument("_id", new ObjectId(key));
- var tp = CurrentTable.DeleteOne(filter);
- var res = new ResultModel
- {
- Success = tp.DeletedCount > 0,
- AffectedRows = (int)tp.DeletedCount
- };
- return res;
- }
- public ResultModel RemoveByObjectId(ObjectId id)
- {
- FilterDefinition<BsonDocument> filter = new BsonDocument("_id", id);
- var tp = CurrentTable.DeleteOne(filter);
- var res = new ResultModel
- {
- Success = tp.DeletedCount > 0,
- AffectedRows = (int)tp.DeletedCount
- };
- return res;
- }
- public ResultModel RemoveMany(string query)
- {
- FilterDefinition<BsonDocument> filter = BsonDocument.Parse(query);
- var tp = CurrentTable.DeleteMany(filter);
- var res = new ResultModel
- {
- Success = tp.DeletedCount > 0,
- AffectedRows = (int)tp.DeletedCount
- };
- return res;
- }
- public ResultModel Update(string key, string set, string arrayFilter = null)
- {
- var filter = new BsonDocument("_id", new ObjectId(key));
- var setDef = BsonDocument.Parse(set);
- UpdateOptions updateOptions = null;
- if (!string.IsNullOrWhiteSpace(arrayFilter))
- {
- var doc = BsonDocument.Parse(arrayFilter);
- var arrayFilterDefinition = new BsonDocumentArrayFilterDefinition<BsonDocument>(doc);
- updateOptions = new UpdateOptions
- {
- ArrayFilters = new List<ArrayFilterDefinition> { arrayFilterDefinition }
- };
- }
- try
- {
- var tp = CurrentTable.UpdateOne(filter, setDef, updateOptions);
- return new ResultModel
- {
- AffectedRows = (int)tp.ModifiedCount,
- Success = tp.ModifiedCount > 0,
- };
- }
- catch (Exception err)
- {
- return new ResultModel($"更新失败,错误信息:{err.Message}");
- }
- }
- public ResultModel UpdateMany(string query, string set, string arrayFilter = null)
- {
- var filter = BsonDocument.Parse(query);
- var setDef = BsonDocument.Parse(set);
- UpdateOptions updateOptions = null;
- if (!string.IsNullOrWhiteSpace(arrayFilter))
- {
- var doc = BsonDocument.Parse(arrayFilter);
- var arrayFilterDefinition = new BsonDocumentArrayFilterDefinition<BsonDocument>(doc);
- updateOptions = new UpdateOptions
- {
- ArrayFilters = new List<ArrayFilterDefinition> { arrayFilterDefinition }
- };
- }
- try
- {
- var tp = CurrentTable.UpdateMany(filter, setDef);
- return new ResultModel
- {
- AffectedRows = (int)tp.ModifiedCount,
- Success = tp.ModifiedCount > 0
- };
- }
- catch (Exception err)
- {
- return new ResultModel($"更新失败,错误信息:{err.Message}");
- }
- }
- public ResultModel Increase(string key, string field, int amount) {
- var filter = new BsonDocument("_id", new ObjectId(key));
- var setDef = BsonDocument.Parse($"{{$inc:{{'{field}':{amount}}}}}");
- UpdateOptions updateOptions = null;
- try
- {
- var tp = CurrentTable.UpdateOne(filter, setDef, updateOptions);
- return new ResultModel
- {
- AffectedRows = (int)tp.ModifiedCount,
- Success = tp.ModifiedCount > 0,
- };
- }
- catch (Exception err)
- {
- return new ResultModel($"更新失败,错误信息:{err.Message}");
- }
- }
- public ResultModel RunCommand(string command)
- {
- throw new NotImplementedException();
- //var res = Database.RunCommand<string>(command);
- }
- public ResultModel AsureTableExist(string tableName)
- {
- ListCollectionsOptions options = new ListCollectionsOptions
- {
- Filter = BsonDocument.Parse($"{{'name':'{tableName}'}}")
- };
- var exist = Database.ListCollections(options).Any();
- if (!exist)
- {
- var res = CreateTable(tableName);
- return res;
- }
- return new ResultModel();
- }
- public ResultModel Insert(string objJson)
- {
- var doc = BsonDocument.Parse(objJson);
- try
- {
- CurrentTable.InsertOne(doc);
- return new ResultModel { Success = true, Data = doc["_id"].ToString()};
- }
- catch (Exception err)
- {
- return new ResultModel($"添加失败,错误信息:{err.Message}");
- }
- }
- public ResultModel InsertBson(BsonDocument doc)
- {
- try
- {
- CurrentTable.InsertOne(doc);
- return new ResultModel { Success = true, Data = doc["_id"].ToString() };
- }
- catch (Exception err)
- {
- return new ResultModel($"添加失败,错误信息:{err.Message}");
- }
- }
- public ResultModel Replace(string key, string objJson)
- {
- var doc = BsonDocument.Parse(objJson);
- var filter = new BsonDocument("_id", new ObjectId(key));
- var tp = CurrentTable.ReplaceOne(filter, doc);
- var res = new ResultModel
- {
- AffectedRows = (int)tp.ModifiedCount,
- Success = tp.ModifiedCount > 0
- };
- return res;
- }
- public ResultModel ReplaceBson(ObjectId key, BsonDocument objBson)
- {
- var filter = new BsonDocument("_id", key);
- var tp = CurrentTable.ReplaceOne(filter, objBson);
- var res = new ResultModel
- {
- AffectedRows = (int)tp.ModifiedCount,
- Success = tp.ModifiedCount > 0
- };
- return res;
- }
- public BsonArray Aggregate(params string[] pipeline)
- {
- IAggregateFluent<BsonDocument> aggregate = CurrentTable.Aggregate<BsonDocument>();
- foreach(var item in pipeline)
- {
- aggregate = aggregate.AppendStage<BsonDocument>(item);
- }
- var res = new BsonArray(aggregate.ToList());
- return res;
- }
- }
- }
|