MongoDB's C # Practice

Source: Internet
Author: User

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.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingMongodb.driver;usingMongodb.bson;usingMongoDB.Driver.Builders;namespacetestmongodb{classProgram { Public Static stringConnectionString ="Mongodb://localhost"; //Database name        Private Static stringDatabaseName ="TestDb"; Static voidMain (string[] args) {            //add a piece of data//Users US = new users () {age = 123, Name = "Testnamea", Sex = "F"}; //us.            Insert (); //Delete a piece of data//Imongoquery iq = new Querydocument ("name", "Testnamea"); //Users.remove (IQ); //Modify a piece of data//Imongoquery iq = new Querydocument ("name", "Testnamea"); //imongoupdate IU = MongoDB.Driver.Builders.Update.Set ("Sex", "M").            Set ("Age", 100); //users.update (IQ, IU); //get a list of data//Imongoquery iq = new Querydocument ("name", "Testnamea");Imongoquery iq = Query.and (Query.gte (" Age", +), Query.matches ("name","/^test/"));//>40List<users> userlist =Users.search (IQ).            ToList (); foreach(Users Iteminchuserlist) {Console.WriteLine (item. Name+" "+item.            SEX); }        }         Public classUsers {Private Static stringTableuser ="Users";  PublicUsers () {} PublicUsers (string name, Int32 age, String sex) {Name=name; Age=Age ; Sex=sex; }             PublicString Name {Get;Set; }  PublicInt32 Age {Get;Set; }  PublicString Sex {Get;Set; }  PublicBoolean Insert () {bsondocument Dom=Newbsondocument {{"name", Name}, {" Age", age}, {"Sex", Sex}}; returnMongohelper.insert (Tableuser, DOM); }             Public StaticIenumerable<users>Search (imongoquery query) {foreach(Bsondocument tmpinchmongohelper.search (tableuser, query))yield return NewUsers (tmp["name"]. Asstring, tmp[" Age"]. AsInt32, tmp["Sex"].            asstring); }             Public StaticBoolean Remove (imongoquery query) {returnmongohelper.remove (tableuser, query); }             Public StaticBoolean Update (imongoquery query, Imongoupdate new_doc) {returnmongohelper.update (tableuser, query, New_doc); }        }         Public Static classMongohelper { Public StaticMongocursor<bsondocument>Search (String collectionname, imongoquery query) {//Defining MONGO ServicesMongoserver Server =mongoserver.create (connectionString); //gets the database that corresponds to DatabaseName, does not exist and is created automaticallyMongodatabase mongodatabase =server.                Getdatabase (DatabaseName); Mongocollection<BsonDocument> collection = mongodatabase.getcollection<bsondocument>(CollectionName); Try                {                    if(Query = =NULL)                        returncollection.                    FindAll (); Else                        returncollection.                Find (query); }                finally{server.                Disconnect (); }            }            /// <summary>            ///New/// </summary>              Public StaticBoolean Insert (String collectionname, bsondocument document) {Mongoserver server=mongoserver.create (connectionString); Mongodatabase Mongodatabase=server.                Getdatabase (DatabaseName); Mongocollection<BsonDocument> collection = mongodatabase.getcollection<bsondocument>(CollectionName); Try{collection.                    Insert (document); Server.                    Disconnect (); return true; }                Catch{server.                    Disconnect (); return false; }            }            /// <summary>            ///Modify/// </summary>               Public StaticBoolean Update (String collectionname, imongoquery query, Imongoupdate new_doc) {Mongoserve R Server=mongoserver.create (connectionString); Mongodatabase Mongodatabase=server.                Getdatabase (DatabaseName); Mongocollection<BsonDocument> collection = mongodatabase.getcollection<bsondocument>(CollectionName); Try{collection.                    Update (query, New_doc); Server.                    Disconnect (); return true; }                Catch{server.                    Disconnect (); return false; }            }            /// <summary>            ///removed from/// </summary>             Public StaticBoolean Remove (String collectionname, imongoquery query) {mongoserver server=mongoserver.create (connectionString); Mongodatabase Mongodatabase=server.                Getdatabase (DatabaseName); Mongocollection<BsonDocument> collection = mongodatabase.getcollection<bsondocument>(CollectionName); Try{collection.                    Remove (query); Server.                    Disconnect (); return true; }                Catch{server.                    Disconnect (); return false; }            }        }    }}

MongoDB's C # 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.