小言_互联网的博客

后端:C#操作Mongodb用法笔记

556人阅读  评论(0)

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。今天主要给大家介绍一下C#编程语言下Mongodb的用法。开发环境为VS2015示例主要包括数据的增删改查、分页查询、文件存储等功能。有需要的朋友可以一起学习一下。

1、需要引用Mongodb程序集

MongoDB.Bson.dll

MongoDB.Driver.dll

2、创建Mongodb工具类库 MongodbHelper.cs


   
  1. using MongoDB.Bson;
  2. using MongoDB.Driver;
  3. using MongoDB.Driver.Builders;
  4. using MongoDB.Driver.GridFS;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Configuration;
  8. using System.IO;
  9. using System.Linq;
  10. namespace MongodbHelper
  11. {
  12. /// <summary>
  13. /// MongoDB的基本增删改查
  14. /// </summary>
  15. public class MongodbTool
  16. {
  17. private readonly MongoDatabase _db;
  18. //数据库默认地址
  19. private readonly string host = ConfigurationManager.AppSettings[ "db_host"];
  20. //数据库默认名称
  21. private readonly string db_name = ConfigurationManager.AppSettings[ "db_name"];
  22. public MongodbTool()
  23. {
  24. var client = new MongoClient(host); //ip及端口
  25. var server = client.GetServer();
  26. _db = server.GetDatabase(db_name); //数据库名称
  27. }
  28. #region 通用增删改查
  29. /// <summary>
  30. /// 新增单个实体模型 modifiy by 2020-11-11
  31. /// </summary>
  32. /// <typeparam name="T"></typeparam>
  33. /// <param name="entity"></param>
  34. /// <returns>True:成功,False:失败</returns>
  35. public bool Insert<T>(T entity)
  36. {
  37. bool isOk = true;
  38. try
  39. {
  40. BsonDocument doc = entity.ToBsonDocument();
  41. WriteConcernResult result = this._db.GetCollection( typeof(T).Name).Insert(doc);
  42. isOk = result.Ok;
  43. }
  44. catch (Exception ex)
  45. {
  46. }
  47. return isOk;
  48. }
  49. /// <summary>
  50. /// 新增实体集合模型
  51. /// </summary>
  52. /// <typeparam name="T"></typeparam>
  53. /// <param name="entity"></param>
  54. /// <returns>True:成功,False:失败</returns>
  55. public bool Add<T>(IEnumerable<T> entity)
  56. {
  57. bool isOk = true;
  58. try
  59. {
  60. int s = 1;
  61. IEnumerable<WriteConcernResult> results = this._db.GetCollection( typeof(T).Name).InsertBatch(entity);
  62. foreach ( var item in results)
  63. {
  64. if (item.Ok)
  65. isOk = true;
  66. else
  67. isOk = false;
  68. }
  69. }
  70. catch (Exception ex)
  71. {
  72. }
  73. return isOk;
  74. }
  75. /// <summary>
  76. /// 查询单条数据
  77. /// </summary>
  78. /// <typeparam name="T"></typeparam>
  79. /// <param name="Field">查询属性字段</param>
  80. /// <param name="Value">字段值</param>
  81. /// <returns>返回当前实体</returns>
  82. public T FindOne<T>(string Field, string Value)
  83. {
  84. T oneEntity = default(T);
  85. try
  86. {
  87. FindOneArgs args = new FindOneArgs
  88. {
  89. Query = Query.EQ(Field, Value)
  90. };
  91. oneEntity = this._db.GetCollection( typeof(T).Name).FindOneAs<T>(args);
  92. this._db.GetCollection( typeof(T).Name).FindAs<T>(Query.GTE(Field, Value)).ToList();
  93. }
  94. catch (Exception ex)
  95. {
  96. }
  97. return oneEntity;
  98. }
  99. /// <summary>
  100. /// 查询多条数据
  101. /// </summary>
  102. /// <typeparam name="T"></typeparam>
  103. /// <param name="Field">查询属性字段</param>
  104. /// <param name="Value">字段值</param>
  105. /// <returns>返回当前实体集合</returns>
  106. public List<T> FindMore<T>(string Field, string Value)
  107. {
  108. List<T> list = new List<T>();
  109. try
  110. {
  111. list = this._db.GetCollection( typeof(T).Name).FindAs<T>(Query.GTE(Field, Value)).ToList();
  112. }
  113. catch (Exception ex)
  114. {
  115. }
  116. return list;
  117. }
  118. /// <summary>
  119. /// 查询文档所有数据
  120. /// </summary>
  121. /// <typeparam name="T"></typeparam>
  122. /// <returns></returns>
  123. public List<T> FindAllMore<T>()
  124. {
  125. List<T> list = new List<T>();
  126. try
  127. {
  128. list = this._db.GetCollection( typeof(T).Name).FindAllAs<T>().ToList();
  129. }
  130. catch (Exception ex)
  131. {
  132. }
  133. return list;
  134. }
  135. /// <summary>
  136. /// 分页查询文档
  137. /// </summary>
  138. /// <typeparam name="T"></typeparam>
  139. /// <param name="pageIndex">页次</param>
  140. /// <param name="pageRow">每页显示记录数</param>
  141. /// <param name="total">总记录数</param>
  142. /// <returns></returns>
  143. public List<T> FindMoreForPage<T>(int pageIndex, int pageRow, ref long total)
  144. {
  145. List<T> list = new List<T>();
  146. try
  147. {
  148. total = this._db.GetCollection( typeof(T).Name).FindAllAs<T>().Count(); //获取总记录数
  149. if (pageIndex == 1)
  150. {
  151. list = this._db.GetCollection( typeof(T).Name).FindAllAs<T>().SetLimit(pageRow).ToList();
  152. }
  153. else
  154. {
  155. var bd = this._db.GetCollection( typeof(T).Name).FindAll().SetSortOrder( "_id:1").SetLimit((pageIndex - 1) * pageRow).Last(); //获取最后一个ID主键
  156. var el = bd.GetElement( 0);
  157. var value = el.Value;
  158. list = this._db.GetCollection( typeof(T).Name).FindAs<T>(Query.GT( "_id", value)).SetSortOrder( "_id:1").SetLimit(pageRow).ToList();
  159. }
  160. }
  161. catch (Exception ex)
  162. {
  163. }
  164. return list;
  165. }
  166. /// <summary>
  167. /// by 2020 ADD
  168. /// </summary>
  169. /// <typeparam name="T"></typeparam>
  170. /// <param name="query">查询条件</param>
  171. /// <param name="pageIndex">当前页</param>
  172. /// <param name="rows">行数</param>
  173. /// <param name="totalCount">总行数</param>
  174. /// <returns></returns>
  175. public List<T> FindPageNewAdd<T>(IMongoQuery query, int pageIndex, int rows, ref long totalCount)
  176. {
  177. List<T> list = new List<T>();
  178. int skipCount = 0;
  179. try
  180. {
  181. if (pageIndex > 1)
  182. {
  183. skipCount = (pageIndex - 1) * rows;
  184. }
  185. else
  186. {
  187. pageIndex = 1;
  188. }
  189. totalCount = this._db.GetCollection( typeof(T).Name).FindAs<T>(query).Count();
  190. if (totalCount > 0)
  191. {
  192. list = this._db.GetCollection( typeof(T).Name).FindAs<T>(query).SetFlags(QueryFlags.NoCursorTimeout).SetSortOrder().SetSkip(skipCount).SetLimit(rows).ToList();
  193. }
  194. }
  195. catch (Exception)
  196. {
  197. throw;
  198. }
  199. return list;
  200. }
  201. /// <summary>
  202. /// 按条件分页查询
  203. /// </summary>
  204. /// <typeparam name="T"></typeparam>
  205. /// <param name="query">查询条件</param>
  206. /// <param name="pageIndex">页次</param>
  207. /// <param name="pageRow">每页显示记录数</param>
  208. /// <param name="total">总记录数</param>
  209. /// <returns></returns>
  210. public List<T> FindMoreForPageByCondion<T>(IMongoQuery query, int pageIndex, int pageRow, ref long total)
  211. {
  212. List<T> list = new List<T>();
  213. try
  214. {
  215. total = this._db.GetCollection( typeof(T).Name).FindAs<T>(query).Count(); //获取总记录数
  216. if (pageIndex == 1)
  217. {
  218. list = this._db.GetCollection( typeof(T).Name).FindAs<T>(query).SetSortOrder(SortBy.Descending( "CreateDate")).SetLimit(pageRow).ToList();
  219. }
  220. else
  221. {
  222. var bd = this._db.GetCollection( typeof(T).Name).Find(query).SetSortOrder( "_id:1").SetLimit((pageIndex - 1) * pageRow).Last(); //获取最后一个ID主键
  223. var el = bd.GetElement( 0);
  224. var value = el.Value;
  225. list = this._db.GetCollection( typeof(T).Name).FindAs<T>(query).SetSortOrder( "_id:1").SetSkip(pageRow).SetLimit(pageRow).ToList();
  226. }
  227. }
  228. catch (Exception ex)
  229. {
  230. }
  231. return list;
  232. }
  233. /// <summary>
  234. /// 更新实体单个字段值
  235. /// </summary>
  236. /// <typeparam name="T"></typeparam>
  237. /// <param name="whereField">条件字段</param>
  238. /// <param name="whereValue">条件字段值</param>
  239. /// <param name="updateField">修改字段</param>
  240. /// <param name="updateValue">修改字段值</param>
  241. /// <returns></returns>
  242. public bool UpdateEntity<T>(string whereField, string whereValue, string updateField, string updateValue)
  243. {
  244. bool isOk = true;
  245. try
  246. {
  247. var query = Query.EQ(whereField, whereValue);
  248. var update = Update.Set(updateField, updateValue);
  249. WriteConcernResult result = this._db.GetCollection( typeof(T).Name).Update(query, update);
  250. if (!result.Ok)
  251. isOk = false;
  252. }
  253. catch (Exception ex)
  254. {
  255. }
  256. return isOk;
  257. }
  258. /// <summary>
  259. /// 更新整个实体模型字段
  260. /// </summary>
  261. /// <typeparam name="T">泛型参数</typeparam>
  262. /// <param name="whereField">条件字段</param>
  263. /// <param name="whereValue">条件值</param>
  264. /// <param name="updateEntity">实体模型</param>
  265. /// <returns>True:成功,False:失败</returns>
  266. public bool UpdateEntityMoreFields<T>(string whereField, string whereValue, T updateEntity)
  267. {
  268. bool isOk = true;
  269. try
  270. {
  271. var query = Query.EQ(whereField, whereValue);
  272. BsonDocument bsonDoc = updateEntity.ToBsonDocument( typeof(T));
  273. var update = new UpdateDocument{
  274. { "$set",bsonDoc}
  275. };
  276. WriteConcernResult result = this._db.GetCollection( typeof(T).Name).Update(query, update);
  277. if (!result.Ok)
  278. isOk = false;
  279. }
  280. catch (Exception ex)
  281. {
  282. }
  283. return isOk;
  284. }
  285. /// <summary>
  286. /// 删除实体文档
  287. /// </summary>
  288. /// <typeparam name="T">泛型参数</typeparam>
  289. /// <param name="whereField">条件字段</param>
  290. /// <param name="whereValue">条件值</param>
  291. /// <returns></returns>
  292. public bool DelEntity<T>(string whereField, string whereValue)
  293. {
  294. bool isOk = true;
  295. try
  296. {
  297. var query = Query.EQ(whereField, whereValue);
  298. WriteConcernResult result = this._db.GetCollection( typeof(T).Name).Remove(query);
  299. if (!result.Ok)
  300. isOk = false;
  301. }
  302. catch (Exception ex)
  303. {
  304. }
  305. return isOk;
  306. }
  307. #endregion
  308. #region GridFS 文件操作
  309. /// <summary>
  310. ///
  311. /// </summary>
  312. /// <returns></returns>
  313. public MongoCursor<MongoGridFSFileInfo> FindAll()
  314. {
  315. return this._db.GetGridFS(MongoGridFSSettings.Defaults).FindAll();
  316. }
  317. /// <summary>
  318. ///
  319. /// </summary>
  320. /// <param name="filePath"></param>
  321. public void UploadFile(string filePath)
  322. {
  323. FileInfo fi = new FileInfo(filePath);
  324. this._db.GetGridFS(MongoGridFSSettings.Defaults).Upload(filePath, fi.Name);
  325. }
  326. /// <summary>
  327. ///
  328. /// </summary>
  329. /// <param name="filePath"></param>
  330. /// <param name="fileName"></param>
  331. public void UploadFile(string filePath, string fileName)
  332. {
  333. this._db.GetGridFS(MongoGridFSSettings.Defaults).Upload(filePath, fileName);
  334. }
  335. /// <summary>
  336. ///下载文件保存到默认目录
  337. /// </summary>
  338. /// <param name="fileName"></param>
  339. /// <param name="filePath"></param>
  340. public void DownloadFile(string fileName)
  341. {
  342. this._db.GetGridFS(MongoGridFSSettings.Defaults).Download(fileName);
  343. }
  344. /// <summary>
  345. ///下载文件保存到其他目录
  346. /// </summary>
  347. /// <param name="fileName"></param>
  348. /// <param name="filePath"></param>
  349. public void DownloadFileOther(string localFileName, string remoteFileName)
  350. {
  351. this._db.GetGridFS(MongoGridFSSettings.Defaults).Download(localFileName,remoteFileName);
  352. }
  353. /// <summary>
  354. ///
  355. /// </summary>
  356. /// <param name="fileName"></param>
  357. public void DeleteFile(string fileName)
  358. {
  359. this._db.GetGridFS(MongoGridFSSettings.Defaults).Delete(fileName);
  360. }
  361. /// <summary>
  362. ///
  363. /// </summary>
  364. public void DeleteAll()
  365. {
  366. foreach ( var inst in this._db.GetGridFS(MongoGridFSSettings.Defaults).FindAll())
  367. {
  368. inst.Delete();
  369. }
  370. }
  371. #endregion
  372. }
  373. }

3、创建实体 User.cs


   
  1. using MongoDB.Bson;
  2. namespace MongoHelper.Model
  3. {
  4. public class User
  5. {
  6. public ObjectId _id;
  7. public string name { get; set; }
  8. public int age { get; set; }
  9. }
  10. }

4、调用示例代码

 

   
  1. var list = new List<User>();
  2. for ( int i = 0; i < 100; i++)
  3. {
  4. User user = new User();
  5. user.age = 20 + i;
  6. user.name = "测试" + i;
  7. list.Add(user);
  8. }
  9. //新增实体
  10. //tool.Add(list);
  11. //更新实体
  12. //tool.UpdateEntity<User>("name", "测试", "age", "99");
  13. //删除操作
  14. //tool.DelEntity<User>("name","测试");
  15. long total = 0;
  16. //构造查询条件
  17. IMongoQuery query = Query.And(
  18. Query.Matches( "name", "1")
  19. );
  20. //分页查询数据
  21. var ll = tool.FindMoreForPageByCondion<User>(query, 0, 10, ref total);
  22. // 文件操作
  23. var model = tool.FindAllMore<User>();
  24. string folder = @"E:\photo";
  25. DirectoryInfo di = new DirectoryInfo(folder);
  26. //循环读取文件上传
  27. foreach ( var file in di.GetFiles())
  28. {
  29. tool.UploadFile(file.FullName, file.Name);
  30. }
  31. var fileModel = tool.FindAll().First();
  32. // 保存文件指定目录
  33. tool.DownloadFileOther( "D:\\"+fileModel.Name, fileModel.Name); //下载文件到当前目录
  34. pictureBox1.ImageLocation = "D:\\"+fileModel.Name;

具体的代码地址:https://gitee.com/hgm1989/mongodb-demo

如有问题可以随时沟通交流。

IT技术分享社区

个人博客网站:https://programmerblog.xyz

文章推荐程序员效率:画流程图常用的工具程序员效率:整理常用的在线笔记软件远程办公:常用的远程协助软件,你都知道吗?51单片机程序下载、ISP及串口基础知识硬件:断路器、接触器、继电器基础知识


转载:https://blog.csdn.net/xishining/article/details/110251355
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场