Mongodb c#增刪改查

寫在前面

最近項目須要,就研究了下mongodb,也是爲了快速上手,就本身弄了一個簡單的例子,這裏記錄一下。mongodb

Mongodb

傳統的關係數據庫通常由數據庫(database)、表(table)、記錄(record)三個層次概念組成,MongoDB是由數據庫(database)、集合(collection)、文檔對象(document)三個層次組成。MongoDB對於關係型數據庫裏的表,可是集合中沒有列、行和關係概念,這體現了模式自由的特色。數據庫

那麼在c#如何使用呢?下面看個例子,你會發現上手很是簡單。c#

要操做數據庫,首先考慮的就是鏈接字符串的問題,由於這就至關於你從那兒拿數據,先要有路子才行。測試

MongoDB 標準鏈接字符串ui

mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]]

mongodb:// 是鏈接字串必須的前綴字串。spa

username:password@ 可選項,鏈接到數據庫後會嘗試驗證登錄。code

host1 必須的指定至少一個host。對象

:portX 可選項,默認鏈接到27017blog

/database 若是指定username:password@,鏈接並驗證登錄指定數據庫。若不指定,默認打開admin數據庫。ip

?options 是鏈接選項。若是不使用/database,則前面須要加上/。全部鏈接選項都是鍵值對name=value,鍵值對之間經過&或;(分號)隔開。

關於options可參考官網的東西。

說這些不如先上個例子,先上手實踐一下。

1          /// <summary>
2         /// 鏈接字符串
3         /// </summary>
4         private static readonly string _connectionString = "mongodb://sa:sa@192.168.1.105: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         }

總結    

到這裏就結束了,這裏弄了一個簡單例子,算是快速上手的例子。

相關文章
相關標籤/搜索