Mongodb c#增刪改查


寫在前面

最近項目需要,就研究了下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: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         }

總結    

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM