mongodb-use C#drivers to realize the deletion, change and check

Source: Internet
Author: User
Tags mongodb version
1. Review: The previous study of MongoDB's basic command learning 2. This article will learn to use the MongoDB C # drivers to implement add-delete and check 3. Preparation: 3.1 C # drivers support situation


In the face of the current learning, we still use the Version2.0 version, because it supports all of the. NET, because the technology is more and more mature;


support for the MongoDB version of the 3.2. NET platform is as follows: all support



3.3 Download

Mongdb C # Drive and make sure you have configured and installed your MongoDB, if the download does not come down, you can point me to download.


4. Use 4.1 References

(1) Open vs2012 and vs2012 version (. NET FrameWork4.5), new project, any project, can test on line, here using console application,

(2) referencing all DLLs;

4.2 Connection Mongdb

Before connecting, ensure that you open the MongoDB service, if you do not remember how to open, please visit: Click to learn to open the service


5. The new MongoDB Operation Tool class took 1 hours to write the tool class and test the test bar. Encapsulates the MONGDB connection, checks and deletions, and creates collections

<pre name= "code" class= "CSharp" >using Mongodb.bson;
Using Mongodb.driver;
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Using System.Threading.Tasks; Namespace MongoDBDemo1 {public class Connection {//CREATE database connection mongoserversettings setting = new Mong
       Oserversettings ();

       Mongoserveraddress address =new mongoserveraddress ("127.0.0.1", 27017);
       Mongoserver server = null; String dbname=string.

       Empty; <summary>///Get Connected///</summary> public Connection () {setting.
           Server = address;
       Server = new Mongoserver (setting); ///<summary>///Constructor gets dbname///</summary>///<param name= "dbname
           "> Database name </param> public Connection (String dbname) {this.dbname = dbname; Setting.
           Server = address;
     Server = new Mongoserver (setting);  ///<summary>///External calls get database///</summary>///<param name= "dbname" >&lt
       ;/param>///<returns></returns> public mongodatabase getmongodatabase (string dbname) {return server.}
       
       Getdatabase (dbname);
       ///<summary>///overload get Database///</summary>///<returns></returns> Public Mongodatabase Getmongodatabase () {return server.
       
       Getdatabase (dbname); ///<summary>///Create collection///</summary>///<param name= "ColName" > Set name </
           param>///<returns></returns> public bool CreateCollection (string colname) {
           Mongodatabase db = This.getmongodatabase (); Commandresult result= db.
           CreateCollection (colname); if (result.
           Ok) {return true; 
    } else       {return false; }///<summary>///external call///</summary>///<param name= "ColName" &

       gt; collection name </param>///<param name= "DB" > Database object </param>///<returns></returns> Public mongocollection<bsondocument> Getmongocoll (string Colname,mongodatabase db) {return db.
       GetCollection (colname); ///<summary>///Internal use///</summary>///<param name= "ColName" > Collection name </ param>///<returns></returns> public mongocollection<bsondocument> getmongocoll (strin G colname) {return this.getmongodatabase ().
       GetCollection (colname); ///<summary>///Query Operations///</summary>///<param name= "ColName" > Collection name Words </param>///<param name= "Query" > Conditions </param>///<returns></returns&Gt Public mongocursor<bsondocument> Select (String colname,imongoquery query) {Mongocollection<bsondocume
           Nt> Mcoll=getmongocoll (colname); try {if (query = = null) {return mcoll.
               FindAll (); else {return mcoll.
               Find (query);
           finally {this.mongoclose (); }}///<summary>///add operations///</summary>///<param name= "ColName" > Collection name </param>///<param name= "Bson" > Single data </param>///<returns></retu Rns> public bool Insert (string colname,bsondocument bson) {MONGOCOLLECTION&LT;BSONDOCUMENT&G T
           Mcoll = Getmongocoll (colname); try {mcoll.
               Insert (Bson);
           return true;
          } catch {return false;
           finally {this.mongoclose (); }///<summary>///add more///</summary>///<param name= "ColName" >
       Collection name </param>///<param name= "Bsonlist" > Data collection </param>///<returns></returns> public bool Insert (string colname, list<bsondocument> bsonlist) {Mongocollection<bsondoc
           ument> mcoll = Getmongocoll (colname); try {foreach (bsondocument Bson in bsonlist) {Mcoll.
               Insert (Bson);
           return true;
           catch {return false;
           
           finally {this.mongoclose (); }///<summary>///modify Operation///</summary>///<param name= "ColName"> collection name </param>///<param name= "Query" > Condition </param>///<param name= "UPD" > Modified content </ param>///<returns></returns> public bool Update (string colname, Imongoquery query,imongoupd
           Ate upd) {mongocollection<bsondocument> mcoll = Getmongocoll (colname); try {mcoll.
               Update (query, UPD);
           return true;
           catch {return false;
           finally {this.mongoclose (); }///<summary>///delete operation///</summary>///<param name= "Cloname" > Collection name </param>///<param name= "Query" > Condition </param>///<param name= "Flag" > is 0, 0 is deleted All information that satisfies the condition </param>///<returns>false/true</returns> public bool Delete (string cloname, IMo Ngoquery query,int flag) {MongocolLection<bsondocument> mcol = This.getmongocoll (cloname); try {if (flag = 0) {mcol.
               Remove (query, Removeflags.none); else {mcol.
               Remove (query, Removeflags.single);
           return true;
           catch {return false;
           finally {this.mongoclose ();
         }///<summary>///close connection///</summary> public void Mongoclose () { Server.
       Disconnect ();
  
 }
    
   }

}



6. Realize the deletion and change check 6.1 UnderstandIf you look at the front of the command line to operate MongoDB, then start 6.3. 6.2 Establishing the connectionInstantiate the connection class, declare the database name, and the collection name.
            String dbname = "Student";
            String colname = "Yuan";
            Connection conn = new Connection (dbname);
6.3 Creating a collectionCall Creation Method
         BOOL Type= conn.createcollection (colname);
            if (type)
            {
                Console.WriteLine ("created successfully.") ");
            }
            else 
            {
                Console.WriteLine ("Create failed.") ");
            }

            Console.readkey ();

6.4 inserting a single piece of information
      Bsondocument Bson = new Bsondocument ("name", "Csdn");
            BOOL Type= Conn.insert (colname, Bson);
            if (type)
            {
                Console.WriteLine ("Increase data success.") ");
            }
            else
            {
                Console.WriteLine ("Failed to add data successfully.") ");
            }

6.5 inserting multiple messages
  Dictionary<string,string> dic=new dictionary<string,string> ();
            Dic. ADD ("Name", "Ming");
            Dic. ADD ("Age", "n");
            Dic. ADD ("Collage", "HPU");
            Dic. ADD ("Sno", "31120907");

            dictionary<string, string> dic1 = new dictionary<string, string> ();
            Dic1. ADD ("name", "Zhuo");
            Dic1. ADD ("Age", "ten");
            Dic1. ADD ("Collage", "HPU");
            Dic1. ADD ("Sno", "31120908");

            list<bsondocument> list = new list<bsondocument> () { 
              new bsondocument (DIC),
              new Bsondocument ( DIC1)
            };

            BOOL Type=conn.insert (colname, list);
            if (type)
            {
                Console.WriteLine ("Increase data success.") ");
            }
            else
            {
                Console.WriteLine ("Failed to add data successfully.") ");
            }
            Console.readkey ();

6.6 Simple Query
     mongocursor<bsondocument> cursor = conn.select (colname, null);
            foreach (bsondocument bson in cursor)
            {
                Console.WriteLine (Bson. ToString ());
            }
            Console.readkey ();

The results are as follows:
6.7 piece Query
    querydocument query
            = new Querydocument ("collage", "HPU");
            mongocursor<bsondocument> cursor = conn.select (colname, query);
            foreach (bsondocument bson in cursor)
            {
                Console.WriteLine (Bson. ToString ());
            }
            Console.readkey ();

The results are as follows:

6.8 Modifying operations
    querydocument query = new Querydocument ("name", "Zhuo");
            dictionary<string, string> dic1 = new dictionary<string, string> ();
            Dic1. ADD ("name", "Zhuo");
            Dic1. ADD ("Age", "n");
            Dic1. ADD ("Collage", "HPU");
            Dic1. ADD ("Sno", "31120908");
            UpdateDocument upd = new UpdateDocument (DIC1);
            BOOL type = conn.update (colname, query, UPD);
            if (type)
            {
                Console.WriteLine ("Modify the data successfully.") ");
            }
            else
            {
                Console.WriteLine ("Failed to modify data.") ");
            }

            View modify Information
            querydocument Query1 = new Querydocument ("name", "Zhuo");
            mongocursor<bsondocument> cursor = Conn.select (colname, query1);
            foreach (bsondocument bson in cursor)
            {
                Console.WriteLine (Bson. ToString ());
            }

            Console.readkey ();

The results are as follows:
6.9 Delete operation
            First query under All
            Console.WriteLine ("I am All");
            mongocursor<bsondocument> cursor = conn.select (colname, null);
            foreach (bsondocument bson in cursor)
            {
                Console.WriteLine (Bson. ToString ());
            }

            Delete querydocument query with age equals 23
            = new Querydocument ("Age", "n");
            The third parameter is 0 o'clock delete all that satisfies the condition, for the other number is to delete only 1
            bool Type=conn.delete (colname, query, 1);

            Console.WriteLine ("I was removed after that.") ");
            mongocursor<bsondocument> Cursor1 = conn.select (colname, null);
            foreach (Bsondocument bson in Cursor1)
            {
                Console.WriteLine (Bson. ToString ());
            }

The effect chart is as follows:



7. Summary: Here only demonstrates simple additions and deletions, followed by a large number of conditional inquiries, but also practice 8. Demo Download

The next article will learn about the use of JAVA driver.

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.