C# 玩转MongoDB(一)

随着NoSQL的应用越来越广泛,很多面试都需要熟悉了解NoSQL【如:Redis,MongoDB等】,本文以一个简单的小例子,简述如何通过C#来操作MongoDB,进行数据的读写操作,仅供学习分享使用,如有不足之处,还请指正。

涉及知识点

  • MongoDB的基础知识,CRUD(增删改查)等【关于MongoDB的基础知识,如果不太了解的,可参考前面几篇博文】。
  • C#面向对象基础知识,WinForm基础编程。

MongoDB驱动安装

项目--右键--管理Nuget程序包--打卡Nuget包管理器--浏览搜索MongoDB.Driver--安装。如下所示:

示例截图

示例虽小,实现了查询,条件查询,明细显示,新增等功能,如下所示:

 

 新增功能

 

C#操作MongoDB步骤

 其实关于数据库的操作步骤,基本上大同小异,如下所示:

  1. 连接服务,得到客户端
  2. 获取要使用的数据库
  3. 获取操作的集合
  4. 执行命令

核心源码

为了代码的公用,本例对MongoDB的操作代码进行了封装,如下所示:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 using MongoDB.Driver;
  7 using MongoDB.Bson;
  8 using MongoDB.Bson.Serialization;
  9 using System.Web.Script.Serialization;
 10 
 11 namespace DemoMongo.Common
 12 {
 13     /// <summary>
 14     /// Mongo帮助类
 15     /// </summary>
 16     public class MongoHelper<T>
 17     {
 18         private string connStr = "";//服务器网址
 19 
 20         private string dbName = "";//数据库名称
 21 
 22         private IMongoClient client;//连接客户端
 23 
 24         private IMongoDatabase db;//连接数据库
 25 
 26         private string collName ;//集合名称
 27 
 28         public MongoHelper() { 
 29         
 30         }
 31 
 32         public MongoHelper(string connStr,string dbName,string collName) {
 33             this.connStr = connStr;
 34             this.dbName = dbName;
 35             this.collName = collName;
 36             this.Init();
 37         }
 38 
 39         /// <summary>
 40         /// 初始化连接客户端
 41         /// </summary>
 42         private void Init()
 43         {
 44             if (client == null)
 45             {
 46                 client = new MongoClient(this.connStr);
 47             }
 48             if (db == null) {
 49                 db = client.GetDatabase(this.dbName);
 50             }
 51         }
 52 
 53         /// <summary>
 54         /// 插入对象
 55         /// </summary>
 56         /// <typeparam name="T"></typeparam>
 57         /// <param name="obj"></param>
 58         public void Insert(T obj)
 59         {
 60             IMongoCollection<T> collention = db.GetCollection<T>(collName);
 61             collention.InsertOneAsync(obj);
 62         }
 63 
 64         /// <summary>
 65         /// 字典形式插入
 66         /// </summary>
 67         /// <param name="dicInfo"></param>
 68         public void Insert(Dictionary<string,string> dicInfo)
 69         {
 70             var collection = db.GetCollection<BsonDocument>(collName);
 71             var document = new BsonDocument(dicInfo);
 72             collection.InsertOne(document);
 73         }
 74 
 75         /// <summary>
 76         /// 无条件查询,即返回全部
 77         /// </summary>
 78         /// <returns></returns>
 79         public List<T> Query() {
 80             var collection = db.GetCollection<BsonDocument>(collName);
 81             var rest =  collection.Find(Builders<BsonDocument>.Filter.Empty);
 82             return rest.As<T>().ToList();
 83         }
 84 
 85         /// <summary>
 86         /// 按名称进行查询
 87         /// </summary>
 88         /// <param name="name"></param>
 89         /// <returns></returns>
 90         public List<T> Query(object name) {
 91             var collection = db.GetCollection<T>(collName);
 92             var rest = collection.Find(Builders<T>.Filter.Eq("name",name));
 93             return rest.As<T>().ToList();
 94         }
 95 
 96 
 97         /// <summary>
 98         /// 只查询一条
 99         /// </summary>
100         /// <param name="Id"></param>
101         /// <returns></returns>
102         public string QueryOne(string Id) { 
103             var collection = db.GetCollection<T>(collName);
104             var rest = collection.Find(Builders<T>.Filter.Eq("Id",new ObjectId(Id))).Limit(1);
105            
106             T t = rest.As<T>().ToList()[0];
107             JavaScriptSerializer jserializer = new JavaScriptSerializer();
108             string strJson = jserializer.Serialize(t);
109             return strJson;
110         }
111     }
112 }

代码调用

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Configuration;
 5 using System.Data;
 6 using System.Drawing;
 7 using System.IO;
 8 using System.Linq;
 9 using System.Text;
10 using System.Threading.Tasks;
11 using System.Windows.Forms;
12 using DemoMongo.Common;
13 
14 namespace DemoMongo
15 {
16     public partial class FrmMain : Form
17     {
18         private MongoHelper<Student> helper;
19 
20         public FrmMain()
21         {
22             InitializeComponent();
23             string connStr = ConfigurationManager.AppSettings["connStr"];
24             string dbName = ConfigurationManager.AppSettings["dbName"];
25             string collName = "student";
26             helper = new MongoHelper<Student>(connStr,dbName,collName);
27 
28         }
29 
30         private void FrmMain_Load(object sender, EventArgs e)
31         {
32             List<Student> list = helper.Query();
33             this.dgView.AutoGenerateColumns = false;
34             this.bsView.DataSource = list;
35             this.dgView.DataSource = bsView;
36         }
37 
38         private void btnQuery_Click(object sender, EventArgs e)
39         {
40             string name = this.txtName.Text.Trim();
41             
42             List<Student> list = new List<Student>();
43             if (string.IsNullOrEmpty(name))
44             {
45                 list = helper.Query();
46             }
47             else {
48                 //注意:此处姓名在MongoDB中存储的数据类型不是固定的,可能是字符串也可能是整数,所以需要判断,否则查询不出来
49                 int name1 = 0;
50                 if (int.TryParse(name, out name1))
51                 {
52                     list = helper.Query(name1);
53                 }
54                 else {
55                     list = helper.Query(name);
56                 }
57                 
58             }
59             this.dgView.AutoGenerateColumns = false;
60             this.bsView.DataSource = list;
61             this.dgView.DataSource = bsView;
62         }
63 
64         private void btnAdd_Click(object sender, EventArgs e)
65         {
66             FrmAdd add = new FrmAdd(this.helper);
67             add.ShowDialog();
68             btnQuery_Click(sender, e);
69         }
70 
71         private void dgView_CellClick(object sender, DataGridViewCellEventArgs e)
72         {
73             //只有当第0列被点击时才生效
74             if (e.ColumnIndex == 0)
75             {
76                 string id = ((Student)dgView.CurrentRow.DataBoundItem).Id.ToString();
77                 string student = helper.QueryOne(id);
78                 this.txtContent.Text = JsonHelper.ConvertJsonString(student);
79             }
80         }
81 
82     }
83 }

以上就是C#对于MongoDB的基础操作,旨在抛砖引玉,共同进步。

备注

踏莎行·候馆梅残

【作者】欧阳修 【朝代】宋
 

候馆梅残,溪桥柳细。草薰风暖摇征辔。离愁渐远渐无穷,迢迢不断如春水。

寸寸柔肠,盈盈粉泪。楼高莫近危阑倚。平芜尽处是春山,行人更在春山外。

 

posted @ 2021-10-07 18:33  老码识途呀  阅读(2996)  评论(3编辑  收藏  举报