MongoDB Learning Section Eighth drive practice

Source: Internet
Author: User
Tags safe mode

As the last article in the series, we have to say that C # drives the operation of MongoDB, there are two types of drivers: official drive and Samus Drive, but I personally prefer the latter.

Because it provides rich LINQ operations, it's quite handy.

Official drive: Https://github.com/mongodb/mongo-csharp-driver/downloads. After downloading, a Help document that resembles MSDN is also available.

Samus Drive: Https://github.com/samus/mongodb-csharp/downloads.

The following is a concrete look at the Samus drive, Https://github.com/samus/mongodb-csharp/blob/master/examples/Simple/Main.cs above provides

A simple demo, in general we'll know how to play.

One: Practice

1: We create a person entity, the Mongoalias attribute represents the alias, where the ID value will overwrite the database automatically generated _id.

1 #region Data entity 2//     <summary> 3//Data entity 4//</summary> 5 Public     class person 6     {7         [Mongoa Lias ("_id")] 8 public         string ID {get; set;} 9 public         string Name {get; set;} All public         int: age {get; set;} Public         DateTime Createtime {get; set;}     }16     #endregion


2: Initialize a number of variables

1         String connectionString = string. Empty; 2  3         string databaseName = string. Empty; 4  5         string collectionname = string. Empty; 6  7         static mongodbhelper<t> MongoDB; 8  9         #region Initialization operation//<SUMMARY>11//initialization operation 12// </summary>13 public         mongodbhelper ()         {             connectionString = "server=127.0.0.1:2222";             DatabaseName = "Shopex";             collectionname = "person";         }19         #endregion

3: In order to facilitate the inheritance class of T using the LINQ feature, we also need to map a bit.

1 #region Mapping configuration for LINQ queries 2//<summary> 3///         to implement the mapping Configuration for LINQ queries 4//</summary> 5 public         Mongoconfigurati On configuration 6         {7             get 8             {9                 var config = new Mongoconfigurationbuilder ();                 config. Mapping (Mapping =>12                 {                     Mapping. DefaultProfile (Profile =>14                     {                         . Subclassesare (t = t.issubclassof (typeof (T)));                     Mapping. Map<t> ();                     mapping. Map<t> ();                 config. ConnectionString (ConnectionString),                 return CONFIG. Buildconfiguration ();             }25         }26         #endregion

4: Here are some basic curd code, similar to writing EF code, and very comfortable to write.

  1 #region Insert operation 2//<summary> 3//INSERT operation 4//</summary> 5//<param name= "Person" >  </param> 6//<returns></returns> 7 public void Insert (T t) 8 {9 using                     (Mongo Mongo = new Mongo (configuration)) Ten {one try 12 {13 Mongo. Connect (); var db = Mongo. Getdatabase (DatabaseName); The var collection = db. Getcollection<t> (CollectionName); Collection. Insert (T, true); Mongo. Disconnect (); (Exception), MONGO. Disconnect (); a throw; #endregion #region Update operation:///&LT;SU Mmary> 35//Update operation://</summary> PNS//<param name= "person" ></param>//<returns></returns>-public void Update (T T, Expression<func<t, bool&                 gt;> func) (Mongo Mongo = new Mongo (configuration)) 42 {43 Try $ {MONGO. Connect (); The var db = Mongo. Getdatabase (DatabaseName); The var collection = db. Getcollection<t> (CollectionName); Collection. Update<t> (T, Func, True); Mongo. Disconnect (); [Exception]------------* MONGO. Disconnect (); (a) a throw; All #endregion #region Get set.//<su Mmary> 67///Get a collection of </summary>//<param name= "person" ></param>//&LT;RETURNS&GT;&LT;/R  Eturns> 71       Public list<t> List (int pageIndex, int. pageSize, Expression<func<t, bool>> Func, out int Pagecoun             T) (PageCount = 0; Mongo Mongo = new Mongo (configuration)) 76 {MONGO. Connect (); The Bayi var db = Mongo. Getdatabase (DatabaseName); The collection var = db. Getcollection<t> (CollectionName); PageCount = Convert.ToInt32 (collection. Count ()); The personlist var = collection. Linq (). Where (func). Skip (PageSize * (pageIndex-1)) 88. Take (pageSize). Select (i = i). ToList (); Mongo. Disconnect (); The personlist return; 94} Exception (MONGO). Disconnect ();       98              Throw }100}101}102 #endregion103 104 #region read a single record.//< SUMMARY&GT;106///read a single record 107//</summary>108//<param name= "person" ></param>109//<returns ></returns>110 Public T (expression<func<t, bool>> Func) 111 {US                     ing (Mongo Mongo = new Mongo (configuration)) 113 {try115 {116 Mongo. Connect (); 117 118 var db = Mongo. Getdatabase (databaseName); 119 var collection = db. Getcollection<t> (CollectionName); 121 122 var single = collection. Linq (). FirstOrDefault (func); 123 124 MONGO.                 Disconnect (); 126 return single;127}129 catch (Exception) 130 {131 MONGO.                    Disconnect (); 132 throw;133}134}135}136 #endregion137 138 #region Delete operation 139// /<summary>140///delete operation 141//</summary>142//<param name= "person" ></param>143//<             returns></returns>144 public void Delete (expression<func<t, bool>> Func) 145 {146                     using (Mongo Mongo = new Mongo (configuration)) 147 {148 try149 {150 Mongo. Connect (); 151 var db = Mongo. Getdatabase (databaseName); 153 154 var collection = db.                     Getcollection<t> (CollectionName); 155 156//This place should be noted that the T parameter must be added, otherwise it will be treated as Object type 157//causes deletion failure 158 Collection. Remove<t> (func); 159 MONGO. Disconnect (); 161 162}163 catch (Exception) 164 {165 Mo Ngo. Disconnect (); 166 THRow;167}168}169}170 #endregion 



5. OK, let's open the 2222 port, because the previous article I have made this MongoDB service, now directly connected to the past, and do a name index.

6. Everything is ready, we do basic operations, such as here I add 1000 data, note that I opened the safe mode, if the insertion is unsuccessful, will throw an exception.

<1> ADD:

1    static void Main (string[] args) 2         {3             mongodbhelper<person> helper = new Mongodbhelper<person > (); 4  5             //INSERT 1000 Data 6 for             (int i = 0; i <; i++) 7             {8                 helper. Insert (New Person () 9                 {ten                     ID = Guid.NewGuid (). ToString (), one                     Name = "Jack" + i,12 Age                     = i,13                     createtime = Datetime.now14                 });             Console.WriteLine ("Insert Success");             console.read ();         

At first glance the data displayed is problematic, why there is no jack0 or jack999, but the find after a bit of a comfortable mood.

<2> update: Get rid of jack941 's name "Mary"

1  static void Main (string[] args) 2         {3             mongodbhelper<person> helper = new Mongodbhelper<person > (); 4  5             //Modify jack941 change to Mary 6             var single = helper. Single (i = I.name = = "jack941"); 7 single             . Name = "Mary"; 8             Helper. Update (single, i = I.id = = single.id); 9             Console.WriteLine ("Modified successfully");             console.read ();         

<3>delete: Delete Mary's record

1      static void Main (string[] args) 2         {3             mongodbhelper<person> helper = new Mongodbhelper<person > (); 4  5             //delete Mary this record 6             helper. Delete (i = I.name = = "Mary"); 7  8             Console.WriteLine ("Delete succeeded"); 9             console.read ();         


<4> list operations: Here I get a list of 9 people in the name.

1    static void Main (string[] args) 2         {3             mongodbhelper<person> helper = new Mongodbhelper<person > (); 4  5             int pagecount; 6  7             //Get the number with 9 in the name 8             var list = helper. List (1, +, I = I.name.contains ("9"), out PageCount); 9            console.read ();         

The total running code

View Code
  1 using System;  2 using System.Collections.Generic;  3 using System.Linq;  4 using System.Text;  5 using System.Configuration;  6 using System.Linq.Expressions;  7 8 using Mongodb.configuration; 9 using Mongodb.linq; Ten using Mongodb.attributes; Namespace Mongodb.test {public class mongodbhelper<t> where T:class + stri ng connectionString = string. Empty; String databaseName = String. Empty; String CollectionName = String. Empty; The static mongodbhelper<t> MongoDB; #region initialization actions://<summary> 27//initialization operation///</summary> public Mongodb Helper () {connectionString = "server=127.0.0.1:2222"; databaseName = "Shopex"; 3 3 CollectionName = "person"; #endregion #region The mapping Configuration of LINQ queries for the implementation of the map of the.//<summary> 39///Implement a Mapping of LINQ queries </summary> $ public mongoconfiguration configuration ($) R config = new Mongoconfigurationbuilder (); The. config. Mapping (Mapping = Mapping. DefaultProfile (Profile) Subclassesare (t = t.issubclassof (typeof (T))); 52}); mapping. Map<t> (); mapping. Map<t> (); 55}); *. config. ConnectionString (ConnectionString); . Buildconfiguration ();  The #region insert operation of the 66///<summary>///insert operation of the #endregion         //</summary> <param name= "person" ></param>//<returns></returns> 70 public void Insert (T-t) (Mongo Mongo = new Mongo (configuration)), {Mongo. Connect (); The var db = Mongo. Getdatabase (DatabaseName); Collection var = db. Getcollection<t> (CollectionName); Bayi collection. Insert (T, true); Mongo. Disconnect (); (Exception) (MONGO). Disconnect (); a throw; 94 #endregion #region Update operation//&LT;SU Mmary> 98///Update///&LT;/SUMMARY&GT;100//<param name= "person" ></param>101//<returns>< /returns>102 public void Update (T T, Expression<func<t, bool>> Func) 103 {104 US          ing (Mongo Mongo = new Mongo (configuration)) 106 try107       {108 MONGO. Connect (); 109 var db = Mongo. Getdatabase (DatabaseName); 111, var collection = db. Getcollection<t> (CollectionName); 113 collection. Update<t> (T, Func, True); Mongo. Disconnect (); 117 118}119 catch (Exception)-{121 mo Ngo. Disconnect (); 122 throw;123}124}125}126 #endregion127 12 8 #region Get collection 129//<summary>130///Get Set 131//</summary>132//<param name= "Person" ; </param>133//<returns></returns>134 public list<t> List (int pageIndex, int pageSize, E             Xpression<func<t, bool>> Func, out int PageCount) 135 {136 PageCount = 0;137 138          using (Mongo Mongo = new Mongo (configuration)) 139 {140       try141 {142 MONGO. Connect (); 143 144 var db = Mongo. Getdatabase (databaseName); 145 146 var collection = db. Getcollection<t> (CollectionName); 147 148 PageCount = Convert.ToInt32 (collection. Count ()); 149 var personlist = collection. Linq (). Where (func). Skip (PageSize * (pageIndex-1)) 151. Take (pageSize). Select (i = i). ToList (); 153 MONGO. Disconnect (); 154 155 return personlist;156 157}158 catch (Exception) 1 Mongo. Disconnect (); 161 throw;162}163}164}165 #endregion166 16 7 #region read a single record 168//<summary>169///read a single record///</summary>171///<param name= "person "></param>172//<returns></returns>173 Public T (expression<func<t, bool>> Func) 174 {175 using                     (Mongo Mongo = new Mongo (configuration)) 176 {177 try178 {179 Mongo. Connect (); 181 var db = Mongo. Getdatabase (databaseName); 182 183 var collection = db. Getcollection<t> (CollectionName); 184 185 var single = collection. Linq (). FirstOrDefault (func); 186 187 Mongo.                 Disconnect (); 188 189 return single;190 191}192 catch (Exception) 193 {194 MONGO. Disconnect (); 195 throw;196}197}198}199 #endregion200 20 1 #region Delete operation 202//<summary>203//delete operation 204//</summary>205//<param name= "Person" &G t;</param>206//<returns></returns>207 public void Delete (expression<func<t, bool>> Func) 208 {209 using (Mongo Mongo = new Mongo (configuration)) 211 {try212 {213 Mongo. Connect (); 214 215 var db = Mongo. Getdatabase (databaseName); 216 217 var collection = db.                     Getcollection<t> (CollectionName); 218 219//This place should be noted that the T parameter must be added, otherwise it will be treated as Object type 220//causes deletion failure 221 Collection. Remove<t> (func); 222 223 MONGO. Disconnect (); 224 225}226 catch (Exception) 227 {228 mo Ngo.     Disconnect (); 229 throw;230}231}232}233 #endregion234     }235 236 #region Data Entity 237//<summary>238//Data entity 239//</summary>240 public class Person241 {242 [Mongoalias ("_id")]243 public StrinG ID {get; set;} 244 245 public string Name {get; set;} 246 247 public int Age {get; set;} 248 249 Public DateTime Createtime {get; set;} }251 #endregion252}

MongoDB Learning Section Eighth drive practice

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.