C # link to mongDB cluster development 3

Source: Internet
Author: User
C # Link mongDB cluster 1 learn about mongdb 2 Deployment cluster 3 C # Link mongdb complete test this chapter continues what we will use in the previous chapter to start using a program to link mondbdb, we all know that the link to sqlserver is actually a Driver written by Microsoft. It has encapsulated some objects and needs to be linked. However

C # Link mongDB cluster 1 learn about mongdb 2 Deployment cluster 3 C # Link mongdb complete test this chapter continues what we will use in the previous chapter to start using a program to link mondbdb, we all know that the link to sqlserver is actually a Driver written by Microsoft. It has encapsulated some objects and needs to be linked. However

C # link to the mongDB Cluster

Mongdb

2. Deploy the Cluster

3 C # Link mongdb to complete the test

C # Link mongdb to complete the test

This chapter continues with the previous chapter. We started to use programs to link to mondbdb. We all know that the link to sqlserver is actually a Driver written by Microsoft. It has encapsulated some objects and needs to be linked. However, we also need some objects to connect to mondbdb. Here is a description on the mongdb official website. You can go and see it yourself or download it directly. Or some of our partners have downloaded it in Chapter 1.

The development driver folder is shown under mongo-csharp-driver-master \ src SRC. Note that I downloaded the driver from vs2012, you can replace the net framework version as needed.

Open the project and you will see

Compile the project to obtain

MongoDB. Bson. dll

MongoDB. Driver. dll

Create a project. The project configuration file is as follows:

 
     
           
       
                    
      
      
      
      
    
 

LogLevel is the custom log level. Check my code later.

LogPath is the Log Path.

MongReplicaSetName is the replica set name, which is actually the name obtained when the cluster is created.

MongoServerAddress is the ip address list of cluster machines. I have opened different ports for different machines here. You can change it to a LAN ip address.

TimeOut time-out time. The default value seems to be 3 seconds. I will set 60 seconds to facilitate debugging.

Main Code of the linked Cluster

////// Obtain the database connection string //////Name of the ettings in the ettings section of the App. Config file///
 
  
Database connection string
 Private static Login Server GetConnStr () {List
 
  
Servers = new List
  
   
(); String reg = @ "^ (? 'Server' \ d {1,}. \ d {1,}. \ d {1,}. \ d {1 ,}):(? 'Port' \ d {1,}) $ "; string [] ServerList = ConfigurationManager. appSettings ["MongoServerAddress"]. trim (). split ('|'); foreach (string server in ServerList) {MatchCollection mc = Regex. matches (server, reg); if (mc! = Null & mc. count> 0) servers. add (new external serveraddress (mc [0]. groups ["server"]. toString (), Convert. toInt32 (mc [0]. groups ["port"]. toString ();} if (servers = null | servers. count <1) return null; Specify clientsettings set = new specify clientsettings (); set. servers = servers; set. replicaSetName = ConfigurationManager. deleetask[ "MongReplicaSetName"]. trim (); // set the replica Set Name int TimeOut = ConvertUtil. pars EInt (ConfigurationManager. appSettings ["TimeOut"]. trim (); // set the replica set name set. connectTimeout = new TimeSpan (0, 0, 0, TimeOut, 0); // set the TimeOut time to 5 seconds. readPreference = new ReadPreference (ReadPreferenceMode. secondaryPreferred); specify client = new specify client (set); return client. getServer ();} set. readPreference = new ReadPreference (ReadPreferenceMode. secondaryPreferred); the code can be modified as needed.
  
 

Nothing else to pay attention

Data insert mongdb code

////// MongDB batch insert statement //////
 
  
Object Type
 ///Database Name///Table Name///Object///Error returned///
 Public static IEnumerable
 
  
Execute
  
   
(String _ databaseName, string _ collectionName, IEnumerable
   
    
Entitys, out string errorMsg) {errorMsg = string. Empty; // gets the database connection IEnumerable
    
     
Result = null; try {if (null = entitys) return null; // obtain the Connected server Cluster _ server = GetConnStr (); // obtain or create a database (if it does not exist ). Relational database = _ server. GetDatabase (_ databaseName); using (_ server. RequestStart (database) // starts to connect to the database. {Collections collection
     
      
MyCollection = database. GetCollection
      
        (_ CollectionName); result = myCollection. InsertBatch
       
         (Entitys) ;}} catch (Exception ex) {errorMsg = ex. ToString () ;}finally {}// record the log if (! String. isNullOrEmpty (errorMsg) {LogUtil. error ("CommonLib. dbAccess. mongDBAccess "," Execute ", errorMsg +" \ n \ r \ t ");} return result ;}
       
      
     
    
   
  
 

Read mongdb data code

////// If you do not know the specific quantity, do not use this function. //////
 //////
 Public static List
 
  
GetAll
  
   
(String _ databaseName, string collectionName, out string errorMsg) {errorMsg = string. Empty; List
   
    
Result = new List
    
     
(); Try {// obtain the Connected server Cluster _ server = GetConnStr (); // obtain the database or create a database (if it does not exist ). Relational database = _ server. GetDatabase (_ databaseName); using (_ server. RequestStart (database) // starts to connect to the database. {Collections collection
     
      
MyCollection = database. GetCollection
      
        (CollectionName); result. AddRange (myCollection. FindAll () ;}} catch (Exception ex) {errorMsg = ex. ToString () ;}// record the log if (! String. isNullOrEmpty (errorMsg) {LogUtil. error ("CommonLib. dbAccess. mongDBAccess "," GetAll ", errorMsg +" \ n \ r \ t ");} return result ;}
      
     
    
   
  
 

The above code is inserted and read.

The subsequent running results are as follows:

I inserted 10 million data records and then read 10 million data records. Efficiency is much faster than SQL Server.

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.