写在前面
最近项目需要,就研究了下mongodb,也是为了快速上手,就自己弄了一个简单的例子,这里记录一下。
Mongodb
传统的关系数据库一般由数据库(database)、表(table)、记录(record)三个层次概念组成,MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。MongoDB对于关系型数据库里的表,但是集合中没有列、行和关系概念,这体现了模式自由的特点。
那么在c#如何使用呢?下面看个例子,你会发现上手非常简单。
要操作数据库,首先考虑的就是连接字符串的问题,因为这就相当于你从那儿拿数据,先要有路子才行。
MongoDB 标准连接字符串
mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]]
mongodb:// 是连接字串必须的前缀字串。
username:password@ 可选项,连接到数据库后会尝试验证登陆。
host1 必须的指定至少一个host。
:portX 可选项,默认连接到27017
/database 如果指定username:password@,连接并验证登陆指定数据库。若不指定,默认打开admin数据库。
?options 是连接选项。如果不使用/database,则前面需要加上/。所有连接选项都是键值对name=value,键值对之间通过&或;(分号)隔开。
关于options可参考官网的东西。
说这些不如先上个例子,先上手实践一下。
1 /// <summary> 2 /// 连接字符串 3 /// </summary> 4 private static readonly string _connectionString = "mongodb://sa:[email protected]:27017/Test_mongo"; 5 private static readonly string _dbName = "Test_mongo";
在c#中使用Mongodb需要引入如下的dll
采用Nuget进行安装就可以了。
增删改查的代码如下:
1 /// <summary>
2 /// 新增
3 /// </summary>
4 /// <param name="customer"></param>
5 private static void Insert(Customer customer)
6 {
7 //创建mogodb对象
8 using (Mongo mongo = new Mongo(_connectionString))
9 {
10 //连接mongodb
11 mongo.Connect();
12 //获得要操作的数据库
13 var db = mongo.GetDatabase(_dbName);
14 //获取要操作的Collection
15 var collection = db.GetCollection<Customer>();
16 collection.Insert(customer);
17 }
18 }
19 /// <summary>
20 /// 批量添加
21 /// </summary>
22 /// <param name="lstCustomer"></param>
23 private static void InsertList(List<Customer> lstCustomer)
24 {
25 using (Mongo mongo = new Mongo(_connectionString))
26 {
27 mongo.Connect();
28 var db = mongo.GetDatabase(_dbName);
29 var collection = db.GetCollection<Customer>();
30 collection.Insert(lstCustomer);
31 }
32 }
33 /// <summary>
34 /// 更新
35 /// </summary>
36 /// <param name="customer"></param>
37 private static void Update(Customer customer)
38 {
39 using (Mongo mongo = new Mongo(_connectionString))
40 {
41 mongo.Connect();
42 var db = mongo.GetDatabase(_dbName);
43 var collection = db.GetCollection<Customer>();
44 //更新对象
45 collection.Update(customer, (x => x.CustomerID == customer.CustomerID));
46 }
47 }
48 /// <summary>
49 /// 获取所有的customer
50 /// </summary>
51 /// <returns></returns>
52 private static IList<Customer> GetList()
53 {
54 using (Mongo mongo = new Mongo(_connectionString))
55 {
56 mongo.Connect();
57 var db = mongo.GetDatabase(_dbName);
58 var collection = db.GetCollection<Customer>();
59 ICursor<Customer> mogoCollection = collection.FindAll();
60
61 return mogoCollection.Documents.ToList();
62 }
63 }
64 /// <summary>
65 /// 根据id获取单个对象
66 /// </summary>
67 /// <param name="customerId"></param>
68 /// <returns></returns>
69 private static Customer GetById(string customerId)
70 {
71 using (Mongo mongo = new Mongo(_connectionString))
72 {
73 mongo.Connect();
74 var db = mongo.GetDatabase(_dbName);
75 var collection = db.GetCollection<Customer>();
76 return collection.FindOne(x => x.CustomerID == customerId);
77 }
78 }
79 }
80 [Serializable]
81 class Customer
82 {
83 [MongoId]
84 public string CustomerID { set; get; }
85 public string CustomerName { set; get; }
86 public string ContactName { set; get; }
87 public string Address { set; get; }
88 public string PostalCode { set; get; }
89 public string Tel { set; get; }
90 }测试
1 static void Main(string[] args)
2 {
3 #region 批量插入
4 //List<Customer> list = new List<Customer>();
5 //for (int i = 0; i < 100; i++)
6 //{
7 // Customer customer = new Customer()
8 // {
9 // CustomerID = Guid.NewGuid().ToString(),
10 // Address = "北京" + i.ToString(),
11 // CustomerName = "wolfy" + i.ToString(),
12 // Tel = "123" + i.ToString(),
13 // PostalCode = "221212" + i.ToString(),
14 // ContactName = "wolfy" + i.ToString()
15 // };
16 // list.Add(customer);
17 //}
18 //InsertList(list);
19 #endregion
20 #region 更新
21 //更新需要先将该对象查询出,然后更新修改的值,不然其他的值为null
22 //Update(new Customer() { CustomerID = "08dca525-fb6d-4984-a55f-53723a6ce39c", ContactName = "wolfy22222" });
23 #endregion
24 #region 查询单个对象和集合
25 //Customer customer = GetById("8211501b-4341-4acb-b2fa-d6a714765443");
26 //Console.WriteLine(new JavaScriptSerializer().Serialize(customer));
27 List<Customer> customers = GetList().ToList();
28 Console.WriteLine(new JavaScriptSerializer().Serialize(customers));
29 #endregion
30 Console.Read();
31 }总结
到这里就结束了,这里弄了一个简单例子,算是快速上手的例子。
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦

