8-day MongoDB-driven practice

Source: Internet
Author: User
As the last article in the series, I have to talk about the C # driver's operations on mongodb. Currently, there are two types of drivers: the official driver and the samus driver, but I personally like the latter, it is quite convenient because it provides a wide range of linq operations. Official DRIVER: github. commongodbmongo-csharp-driverdownloads. After the download, we also provide

As the last article in the series, I have to talk about the C # driver's operations on mongodb. Currently, there are two types of drivers: the official driver and the samus driver, but I personally like the latter, it is quite convenient because it provides a wide range of linq operations. Official DRIVER: https://github.com/mongodb/developer-csharp-driver/downloads. After the download, we also provide

As the last article in the series, I have to talk about the C # driver's operations on mongodb. Currently, there are two types of drivers: the official driver and the samus driver, but I personally like the latter,

It is quite convenient because it provides a wide range of linq operations.

Official DRIVER: https://github.com/mongodb/developer-csharp-driver/downloads. After the download, a help document similar to msdn is provided.

Samus DRIVER: https://github.com/samus/mongodb-csharp/downloads.

Next let's take a look at the samus driver, https://github.com/samus/mongodb-csharp/blob/master/examples/simple/main.cs ##

A simple demo. Let's take a look at how we can play it.

I. Practice

1: We create a Person entity. The alias feature indicates taking an alias. The ID value here will overwrite the automatically generated _ id of the database.


# Region data entity ////// Data entity ///Public class Person {[Keep alias ("_ id")] public string ID {get; set;} public string Name {get; set;} public int Age {get; set ;} public DateTime CreateTime {get; set ;}# endregion


2. initialize some variables.


String connectionString = string. Empty; string databaseName = string. Empty; string collectionName = string. Empty; static MongodbHelper
 
  
Mongodb; # region initialization operation ///
  /// Initialization operation ///Public MongodbHelper () {connectionString = "Server = 127.0.0.1: 2222"; databaseName = "shopex"; collectionName = "person" ;}# endregion
 

3: to facilitate the use of the linq function for the T inheritance class, we also need to map it.

# Region linq ing configuration for linq query ////// Implement the linq ing configuration of the linq query ///Public configuration {get {var config = new configurationbuilder (); config. mapping (mapping => {mapping. defaultProfile (profile => {profile. subClassesAre (t => t. isSubclassOf (typeof (T) ;}); mapping. map
 
  
(); Mapping. Map
  
   
() ;}); Config. ConnectionString (connectionString); return config. BuildConfiguration () ;}# endregion
  
 

4: below are some basic CURD code, which is similar to writing EF code and comfortable to write.


# Region insert operation ////// Insert operation /////////
 Public void Insert (T t) {using (Mongo mongo = new Mongo (configuration) {try {mongo. connect (); var db = mongo. getDatabase (databaseName); var collection = db. getCollection
 
  
(CollectionName); collection. insert (t, true); mongo. disconnect ();} catch (Exception) {mongo. disconnect (); throw ;}}# endregion # region update operation ///
  /// Update operation //////
  ///
  Public void Update (T t, Expression
  
   
> Func) {using (Mongo mongo = new Mongo (configuration) {try {mongo. Connect (); var db = mongo. GetDatabase (databaseName); var collection = db. GetCollection
   
    
(CollectionName); collection. Update
    
     
(T, func, true); mongo. Disconnect () ;}catch (Exception) {mongo. Disconnect (); throw ;}}# endregion # region gets the set ///
     /// Obtain the set //////
     ///
     Public List
     
      
List (int pageIndex, int pageSize, Expression
      
        > Func, out int pageCount) {pageCount = 0; using (Mongo mongo = new Mongo (configuration) {try {mongo. connect (); var db = mongo. getDatabase (databaseName); var collection = db. getCollection
       
         (CollectionName); pageCount = Convert. toInt32 (collection. count (); var personList = collection. linq (). where (func ). skip (pageSize * (pageIndex-1 )). take (pageSize ). select (I => I ). toList (); mongo. disconnect (); return personList;} catch (Exception) {mongo. disconnect (); throw ;}}# endregion # region reads a single record ///
        /// Read a single record //////
        ///
        Public T Single (Expression
        
          > Func) {using (Mongo mongo = new Mongo (configuration) {try {mongo. Connect (); var db = mongo. GetDatabase (databaseName); var collection = db. GetCollection
         
           (CollectionName); var single = collection. linq (). firstOrDefault (func); mongo. disconnect (); return single;} catch (Exception) {mongo. disconnect (); throw ;}}# endregion # region delete operation ///
          /// Delete operation //////
          ///
          Public void Delete (Expression
          
            > Func) {using (Mongo mongo = new Mongo (configuration) {try {mongo. Connect (); var db = mongo. GetDatabase (databaseName); var collection = db. GetCollection
           
             (CollectionName); // note that the T parameter must be added; otherwise, it will be treated as an object type. // this will cause the collection to fail to be deleted. Remove
            
              (Func); mongo. Disconnect ();} catch (Exception) {mongo. Disconnect (); throw ;}# endregion
            
           
          
         
        
       
      
     
    
   
  
 

5. Okay. Let's open port 2222. As I have already made this mongodb service in the previous article, now I have connected it directly and made a Name index.

6. Everything is ready. Let's perform basic operations. For example, here I add one thousand pieces of data. Note that the security mode is enabled. If the insertion fails, an exception will be thrown.

<1> Add:


Static void Main (string [] args) {MongodbHelper
 
  
Helper = new MongodbHelper
  
   
(); // Insert 1000 data records for (int I = 0; I <1000; I ++) {helper. insert (new Person () {ID = Guid. newGuid (). toString (), Name = "jack" + I, Age = I, CreateTime = DateTime. now});} Console. writeLine ("inserted successfully"); Console. read ();}
  
 

At first glance, I thought there was a problem with the data. Why didn't jack0 or jack999 appear.

<2> update: here, the name of jack941 is changed to "mary"



Static void Main (string [] args) {MongodbHelper
 
  
Helper = new MongodbHelper
  
   
(); // Change jack941 to mary var single = helper. single (I => I. name = "jack941"); single. name = "mary"; helper. update (single, I => I. ID = single. ID); Console. writeLine ("modified successfully"); Console. read ();}
  
 

<3> Delete: Delete the mary record.


Static void Main (string [] args) {MongodbHelper
 
  
Helper = new MongodbHelper
  
   
(); // Delete the mary record helper. delete (I => I. name = "mary"); Console. writeLine ("deleted successfully"); Console. read ();}
  
 


<4> list Operation: here, I will obtain the list of people whose names contain 9.


Static void Main (string [] args) {MongodbHelper
 
  
Helper = new MongodbHelper
  
   
(); Int pagecount; // get the number of people with 9 in the name var list = helper. list (1, 20, I => I. name. contains ("9"), out pagecount); Console. read ();}
  
 

Total Running code


Using System; using System. collections. generic; using System. linq; using System. text; using System. configuration; using System. linq. expressions; using MongoDB. configuration; using MongoDB. linq; using MongoDB. attributes; namespace MongoDB. test {public class MongodbHelper
 
  
Where T: class {string connectionString = string. Empty; string databaseName = string. Empty; string collectionName = string. Empty; static MongodbHelper
  
   
Mongodb; # region initialization operation ///
   /// Initialization operation ///Public MongodbHelper () {connectionString = "Server = 127.0.0.1: 2222"; databaseName = "shopex"; collectionName = "person ";} # endregion # configure the linq ing of the region Implementation of linq query ///
   /// Implement the linq ing configuration of the linq query ///Public configuration {get {var config = new configurationbuilder (); config. mapping (mapping => {mapping. defaultProfile (profile => {profile. subClassesAre (t => t. isSubclassOf (typeof (T) ;}); mapping. map
   
    
(); Mapping. Map
    
     
() ;}); Config. ConnectionString (connectionString); return config. BuildConfiguration () ;}# endregion # region insert operation ///
     /// Insert operation //////
     ///
     Public void Insert (T t) {using (Mongo mongo = new Mongo (configuration) {try {mongo. connect (); var db = mongo. getDatabase (databaseName); var collection = db. getCollection
     
      
(CollectionName); collection. insert (t, true); mongo. disconnect ();} catch (Exception) {mongo. disconnect (); throw ;}}# endregion # region update operation ///
      /// Update operation //////
      ///
      Public void Update (T t, Expression
      
        > Func) {using (Mongo mongo = new Mongo (configuration) {try {mongo. Connect (); var db = mongo. GetDatabase (databaseName); var collection = db. GetCollection
       
         (CollectionName); collection. Update
        
          (T, func, true); mongo. Disconnect () ;}catch (Exception) {mongo. Disconnect (); throw ;}}# endregion # region gets the set ///
         /// Obtain the set //////
         ///
         Public List
         
           List (int pageIndex, int pageSize, Expression
          
            > Func, out int pageCount) {pageCount = 0; using (Mongo mongo = new Mongo (configuration) {try {mongo. connect (); var db = mongo. getDatabase (databaseName); var collection = db. getCollection
           
             (CollectionName); pageCount = Convert. toInt32 (collection. count (); var personList = collection. linq (). where (func ). skip (pageSize * (pageIndex-1 )). take (pageSize ). select (I => I ). toList (); mongo. disconnect (); return personList;} catch (Exception) {mongo. disconnect (); throw ;}}# endregion # region reads a single record ///
            /// Read a single record //////
            ///
            Public T Single (Expression
            
              > Func) {using (Mongo mongo = new Mongo (configuration) {try {mongo. Connect (); var db = mongo. GetDatabase (databaseName); var collection = db. GetCollection
             
               (CollectionName); var single = collection. linq (). firstOrDefault (func); mongo. disconnect (); return single;} catch (Exception) {mongo. disconnect (); throw ;}}# endregion # region delete operation ///
              /// Delete operation //////
              ///
              Public void Delete (Expression
              
                > Func) {using (Mongo mongo = new Mongo (configuration) {try {mongo. Connect (); var db = mongo. GetDatabase (databaseName); var collection = db. GetCollection
               
                 (CollectionName); // note that the T parameter must be added; otherwise, it will be treated as an object type. // this will cause the collection to fail to be deleted. Remove
                
                  (Func); mongo. Disconnect ();} catch (Exception) {mongo. Disconnect (); throw ;}}# endregion }# region data entity ///
                 /// Data entity ///Public class Person {[Keep alias ("_ id")] public string ID {get; set;} public string Name {get; set;} public int Age {get; set ;} public DateTime CreateTime {get; set ;}# endregion}
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
 

Wow, taking the three-day vacation, has finally finished writing this series. Thank you for your interest in this series.


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.