MongoRepository.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. using CZFW.Core;
  2. using CZFW.Framework.Model;
  3. using CZFW.Framework.Model.ViewModel;
  4. using MongoDB.Bson;
  5. using MongoDB.Driver;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Threading.Tasks;
  10. namespace CZFW.MDB
  11. {
  12. public class MongoRepository : IMongoRepository
  13. {
  14. public MongoRepository()
  15. {
  16. }
  17. public MongoRepository(string tableName)
  18. {
  19. currentTableName = tableName;
  20. }
  21. private IMongoDatabase server;
  22. public IMongoDatabase Database
  23. {
  24. get
  25. {
  26. if (server is null)
  27. {
  28. var conStr = ConfigHelper.GetValue<string>("ConnectionStrings:MongoConnection");
  29. var client = new MongoClient(conStr);
  30. var dbName = ConfigHelper.GetValue<string>("ConnectionStrings:DbName");
  31. server = client.GetDatabase(dbName);
  32. }
  33. return server;
  34. }
  35. set { server = value; }
  36. }
  37. private string currentTableName;
  38. public string CurrentTableName
  39. {
  40. get
  41. {
  42. if (string.IsNullOrWhiteSpace(currentTableName))
  43. throw new Exception("尚未指定当前操作集合名称!");
  44. return currentTableName;
  45. }
  46. set { currentTableName = value; }
  47. }
  48. private IMongoCollection<BsonDocument> currentTable;
  49. public IMongoCollection<BsonDocument> CurrentTable
  50. {
  51. get
  52. {
  53. if (currentTable == null)
  54. currentTable = Database.GetCollection<BsonDocument>(CurrentTableName);
  55. return currentTable;
  56. }
  57. set
  58. {
  59. currentTable = value;
  60. }
  61. }
  62. public Task<ResultModel> CopyTableAsync(string srcTableName, string destTableName, bool copyData = false)
  63. {
  64. throw new NotImplementedException();
  65. }
  66. public async Task<ResultModel> CreateTableAsync(string tableName, CreateCollectionOptions options = null)
  67. {
  68. try
  69. {
  70. await Database.CreateCollectionAsync(tableName, options);
  71. return new ResultModel();
  72. }
  73. catch (Exception err)
  74. {
  75. return new ResultModel($"创建失败,错误信息:{err}");
  76. }
  77. }
  78. public async Task<long> GetCountAsync(string query = null)
  79. {
  80. if (string.IsNullOrWhiteSpace(query))
  81. query = "{}";
  82. var filter = BsonDocument.Parse(query);
  83. var res = await CurrentTable.CountAsync(filter);
  84. return res;
  85. }
  86. public async Task<dynamic> GetOneAsync(string query)
  87. {
  88. var filter = BsonDocument.Parse(query);
  89. var res = await CurrentTable.FindAsync(filter);
  90. dynamic tp = res.FirstOrDefault();
  91. return tp;
  92. }
  93. public async Task<dynamic> GetAsync(string key)
  94. {
  95. var filter = new BsonDocument("_id", new ObjectId(key));
  96. var res = await CurrentTable.FindAsync(filter);
  97. dynamic tp = res.FirstOrDefault();
  98. return tp;
  99. }
  100. public async Task<(dynamic data, PagerModel pager)> GetListAsync(string query = "{}", string sort = null, string projection = null, int pageIndex = 1, int pageSize = 20)
  101. {
  102. var filter = BsonDocument.Parse(query);
  103. SortDefinition<BsonDocument> sortDef = string.IsNullOrWhiteSpace(sort) ? BsonDocument.Parse(sort) : null;
  104. ProjectionDefinition<BsonDocument> projectionDef = string.IsNullOrWhiteSpace(projection) ? BsonDocument.Parse(projection) : null;
  105. var option = new FindOptions<BsonDocument, BsonDocument>();
  106. long count = CurrentTable.Count(filter);
  107. PagerModel pager = null;
  108. if (pageIndex > 0)
  109. {
  110. option.Limit = pageIndex;
  111. option.Skip = (pageIndex - 1) * pageSize;
  112. pager = new PagerModel((int)count, pageIndex, pageSize);
  113. }
  114. option.Sort = sortDef;
  115. option.Projection = projectionDef;
  116. var res = await CurrentTable.FindAsync(filter, option);
  117. dynamic tp = res.ToList();
  118. return (tp, pager);
  119. }
  120. public async Task<ResultModel> RemoveAsync(string key)
  121. {
  122. FilterDefinition<BsonDocument> filter = new BsonDocument("_id", new ObjectId(key));
  123. var tp = await CurrentTable.DeleteOneAsync(filter);
  124. var res = new ResultModel
  125. {
  126. Success = tp.DeletedCount > 0,
  127. AffectedRows = (int)tp.DeletedCount
  128. };
  129. return res;
  130. }
  131. public async Task<ResultModel> RemoveManyAsync(string query)
  132. {
  133. FilterDefinition<BsonDocument> filter = BsonDocument.Parse(query);
  134. var tp = await CurrentTable.DeleteManyAsync(filter);
  135. var res = new ResultModel
  136. {
  137. Success = tp.DeletedCount > 0,
  138. AffectedRows = (int)tp.DeletedCount
  139. };
  140. return res;
  141. }
  142. public async Task<ResultModel> RemoveTableAsync(string tableName)
  143. {
  144. try
  145. {
  146. await Database.DropCollectionAsync(tableName);
  147. return new ResultModel();
  148. }
  149. catch (Exception err)
  150. {
  151. return new ResultModel($"删除表失败,错误信息:{err.Message}");
  152. }
  153. }
  154. //public async Task<ResultModel> RunCommandAsync(string command)
  155. //{
  156. // throw new NotImplementedException();
  157. //}
  158. public async Task<ResultModel> UpdateAsync(string key, string set, string arrayFilter = null)
  159. {
  160. var filter = new BsonDocument("_id", new ObjectId(key));
  161. var setDef = BsonDocument.Parse(set);
  162. UpdateOptions updateOptions = null;
  163. if (!string.IsNullOrWhiteSpace(arrayFilter))
  164. {
  165. var doc = BsonDocument.Parse(arrayFilter);
  166. var arrayFilterDefinition = new BsonDocumentArrayFilterDefinition<BsonDocument>(doc);
  167. updateOptions = new UpdateOptions
  168. {
  169. ArrayFilters = new List<ArrayFilterDefinition> { arrayFilterDefinition }
  170. };
  171. }
  172. try
  173. {
  174. var tp = await CurrentTable.UpdateOneAsync(filter, setDef, updateOptions);
  175. return new ResultModel
  176. {
  177. AffectedRows = (int)tp.ModifiedCount,
  178. Success = tp.ModifiedCount > 0,
  179. };
  180. }
  181. catch (Exception err)
  182. {
  183. return new ResultModel($"更新失败,错误信息:{err.Message}");
  184. }
  185. }
  186. public async Task<ResultModel> UpdateManyAsync(string query, string set, string arrayFilter = null)
  187. {
  188. var filter = BsonDocument.Parse(query);
  189. var setDef = BsonDocument.Parse(set);
  190. UpdateOptions updateOptions = null;
  191. if (!string.IsNullOrWhiteSpace(arrayFilter))
  192. {
  193. var doc = BsonDocument.Parse(arrayFilter);
  194. var arrayFilterDefinition = new BsonDocumentArrayFilterDefinition<BsonDocument>(doc);
  195. updateOptions = new UpdateOptions
  196. {
  197. ArrayFilters = new List<ArrayFilterDefinition> { arrayFilterDefinition }
  198. };
  199. }
  200. try
  201. {
  202. var tp = await CurrentTable.UpdateManyAsync(filter, setDef, updateOptions);
  203. return new ResultModel
  204. {
  205. AffectedRows = (int)tp.ModifiedCount,
  206. Success = tp.ModifiedCount > 0
  207. };
  208. }
  209. catch (Exception err)
  210. {
  211. return new ResultModel($"更新失败,错误信息:{err.Message}");
  212. }
  213. }
  214. public void SetCurrentTable(string tableName)
  215. {
  216. if(currentTableName!=tableName)
  217. {
  218. currentTableName = tableName;
  219. currentTable = null;
  220. }
  221. }
  222. public IMongoCollection<BsonDocument> GetTable(string tableName)
  223. {
  224. var table = Database.GetCollection<BsonDocument>(tableName);
  225. return table;
  226. }
  227. public BsonDocument Get(string key, string projection="{}")
  228. {
  229. var filter = new BsonDocument("_id", new ObjectId(key));
  230. var res = CurrentTable.Find(filter).Project(projection).FirstOrDefault();
  231. return res;
  232. }
  233. public BsonDocument GetOne(string query = "{}", string projection = "{}", string sort="{}")
  234. {
  235. var filter = BsonDocument.Parse(query);
  236. var res = CurrentTable.Find(filter).Project(projection).Sort(sort).FirstOrDefault();
  237. return res;
  238. }
  239. public BsonArray GetList(string query ="{}", string projection="{}", int pageIndex=1,int pageSize=20, string sort="{}", bool useCursor=false)
  240. {
  241. var filter = BsonDocument.Parse(query);
  242. var projectionDef = BsonDocument.Parse(projection);
  243. var find = CurrentTable.Find(filter).Project<BsonDocument>(projectionDef).Sort(sort).Skip((pageIndex-1)*pageSize).Limit(pageSize);
  244. if (!useCursor)
  245. return new BsonArray(find.ToList());
  246. var bsonarray = new BsonArray();
  247. foreach (var item in find.ToEnumerable())
  248. {
  249. bsonarray.Add(item);
  250. }
  251. return bsonarray;
  252. }
  253. public long GetCount(string query = null)
  254. {
  255. if (string.IsNullOrWhiteSpace(query))
  256. query = "{}";
  257. var filter = BsonDocument.Parse(query);
  258. var res = CurrentTable.Count(filter);
  259. return res;
  260. }
  261. public ResultModel CreateTable(string tableName, CreateCollectionOptions options = null)
  262. {
  263. try
  264. {
  265. Database.CreateCollection(tableName, options);
  266. return new ResultModel();
  267. }
  268. catch (Exception err)
  269. {
  270. return new ResultModel($"创建失败,错误信息:{err}");
  271. }
  272. }
  273. public ResultModel RemoveTable(string tableName)
  274. {
  275. try
  276. {
  277. Database.DropCollection(tableName);
  278. return new ResultModel();
  279. }
  280. catch (Exception err)
  281. {
  282. return new ResultModel($"删除表失败,错误信息:{err.Message}");
  283. }
  284. }
  285. public ResultModel CopyTable(string srcTableName, string destTableName, bool copyData = false)
  286. {
  287. throw new NotImplementedException();
  288. }
  289. public ResultModel Remove(string key)
  290. {
  291. FilterDefinition<BsonDocument> filter = new BsonDocument("_id", new ObjectId(key));
  292. var tp = CurrentTable.DeleteOne(filter);
  293. var res = new ResultModel
  294. {
  295. Success = tp.DeletedCount > 0,
  296. AffectedRows = (int)tp.DeletedCount
  297. };
  298. return res;
  299. }
  300. public ResultModel RemoveByObjectId(ObjectId id)
  301. {
  302. FilterDefinition<BsonDocument> filter = new BsonDocument("_id", id);
  303. var tp = CurrentTable.DeleteOne(filter);
  304. var res = new ResultModel
  305. {
  306. Success = tp.DeletedCount > 0,
  307. AffectedRows = (int)tp.DeletedCount
  308. };
  309. return res;
  310. }
  311. public ResultModel RemoveMany(string query)
  312. {
  313. FilterDefinition<BsonDocument> filter = BsonDocument.Parse(query);
  314. var tp = CurrentTable.DeleteMany(filter);
  315. var res = new ResultModel
  316. {
  317. Success = tp.DeletedCount > 0,
  318. AffectedRows = (int)tp.DeletedCount
  319. };
  320. return res;
  321. }
  322. public ResultModel Update(string key, string set, string arrayFilter = null)
  323. {
  324. var filter = new BsonDocument("_id", new ObjectId(key));
  325. var setDef = BsonDocument.Parse(set);
  326. UpdateOptions updateOptions = null;
  327. if (!string.IsNullOrWhiteSpace(arrayFilter))
  328. {
  329. var doc = BsonDocument.Parse(arrayFilter);
  330. var arrayFilterDefinition = new BsonDocumentArrayFilterDefinition<BsonDocument>(doc);
  331. updateOptions = new UpdateOptions
  332. {
  333. ArrayFilters = new List<ArrayFilterDefinition> { arrayFilterDefinition }
  334. };
  335. }
  336. try
  337. {
  338. var tp = CurrentTable.UpdateOne(filter, setDef, updateOptions);
  339. return new ResultModel
  340. {
  341. AffectedRows = (int)tp.ModifiedCount,
  342. Success = tp.ModifiedCount > 0,
  343. };
  344. }
  345. catch (Exception err)
  346. {
  347. return new ResultModel($"更新失败,错误信息:{err.Message}");
  348. }
  349. }
  350. public ResultModel UpdateMany(string query, string set, string arrayFilter = null)
  351. {
  352. var filter = BsonDocument.Parse(query);
  353. var setDef = BsonDocument.Parse(set);
  354. UpdateOptions updateOptions = null;
  355. if (!string.IsNullOrWhiteSpace(arrayFilter))
  356. {
  357. var doc = BsonDocument.Parse(arrayFilter);
  358. var arrayFilterDefinition = new BsonDocumentArrayFilterDefinition<BsonDocument>(doc);
  359. updateOptions = new UpdateOptions
  360. {
  361. ArrayFilters = new List<ArrayFilterDefinition> { arrayFilterDefinition }
  362. };
  363. }
  364. try
  365. {
  366. var tp = CurrentTable.UpdateMany(filter, setDef);
  367. return new ResultModel
  368. {
  369. AffectedRows = (int)tp.ModifiedCount,
  370. Success = tp.ModifiedCount > 0
  371. };
  372. }
  373. catch (Exception err)
  374. {
  375. return new ResultModel($"更新失败,错误信息:{err.Message}");
  376. }
  377. }
  378. public ResultModel Increase(string key, string field, int amount) {
  379. var filter = new BsonDocument("_id", new ObjectId(key));
  380. var setDef = BsonDocument.Parse($"{{$inc:{{'{field}':{amount}}}}}");
  381. UpdateOptions updateOptions = null;
  382. try
  383. {
  384. var tp = CurrentTable.UpdateOne(filter, setDef, updateOptions);
  385. return new ResultModel
  386. {
  387. AffectedRows = (int)tp.ModifiedCount,
  388. Success = tp.ModifiedCount > 0,
  389. };
  390. }
  391. catch (Exception err)
  392. {
  393. return new ResultModel($"更新失败,错误信息:{err.Message}");
  394. }
  395. }
  396. public ResultModel RunCommand(string command)
  397. {
  398. throw new NotImplementedException();
  399. //var res = Database.RunCommand<string>(command);
  400. }
  401. public ResultModel AsureTableExist(string tableName)
  402. {
  403. ListCollectionsOptions options = new ListCollectionsOptions
  404. {
  405. Filter = BsonDocument.Parse($"{{'name':'{tableName}'}}")
  406. };
  407. var exist = Database.ListCollections(options).Any();
  408. if (!exist)
  409. {
  410. var res = CreateTable(tableName);
  411. return res;
  412. }
  413. return new ResultModel();
  414. }
  415. public ResultModel Insert(string objJson)
  416. {
  417. var doc = BsonDocument.Parse(objJson);
  418. try
  419. {
  420. CurrentTable.InsertOne(doc);
  421. return new ResultModel { Success = true, Data = doc["_id"].ToString()};
  422. }
  423. catch (Exception err)
  424. {
  425. return new ResultModel($"添加失败,错误信息:{err.Message}");
  426. }
  427. }
  428. public ResultModel InsertBson(BsonDocument doc)
  429. {
  430. try
  431. {
  432. CurrentTable.InsertOne(doc);
  433. return new ResultModel { Success = true, Data = doc["_id"].ToString() };
  434. }
  435. catch (Exception err)
  436. {
  437. return new ResultModel($"添加失败,错误信息:{err.Message}");
  438. }
  439. }
  440. public ResultModel Replace(string key, string objJson)
  441. {
  442. var doc = BsonDocument.Parse(objJson);
  443. var filter = new BsonDocument("_id", new ObjectId(key));
  444. var tp = CurrentTable.ReplaceOne(filter, doc);
  445. var res = new ResultModel
  446. {
  447. AffectedRows = (int)tp.ModifiedCount,
  448. Success = tp.ModifiedCount > 0
  449. };
  450. return res;
  451. }
  452. public ResultModel ReplaceBson(ObjectId key, BsonDocument objBson)
  453. {
  454. var filter = new BsonDocument("_id", key);
  455. var tp = CurrentTable.ReplaceOne(filter, objBson);
  456. var res = new ResultModel
  457. {
  458. AffectedRows = (int)tp.ModifiedCount,
  459. Success = tp.ModifiedCount > 0
  460. };
  461. return res;
  462. }
  463. public BsonArray Aggregate(params string[] pipeline)
  464. {
  465. IAggregateFluent<BsonDocument> aggregate = CurrentTable.Aggregate<BsonDocument>();
  466. foreach(var item in pipeline)
  467. {
  468. aggregate = aggregate.AppendStage<BsonDocument>(item);
  469. }
  470. var res = new BsonArray(aggregate.ToList());
  471. return res;
  472. }
  473. }
  474. }