Manipulating MongoDB with C # (demo included)

Source: Internet
Author: User
Tags mongoclient

Because of the need to write a generic-based helper, it is easier to use.

For the sake of the people do not repeat the wheel, so sent to hope to help who.

Complex queries are best used with LINQ, which is also the official advice of MongoDB.

MongoDB's C # configuration

This part of a lot of articles are mentioned, it is necessary to note that the driver with your version of MongoDB and you. NET seems to have a relationship

I'm mongodb-2.x,.net4,driver, I'm using a 1.x series.

2.x series It seems that I can not afford to use this configuration, we may try, seemingly want. NET to 4.5.

Driven:

Https://github.com/mongodb/mongo-csharp-driver

Here is a small pit, MongoDB database connection string and MySQL is not the same, many articles did not mention the full connection string, spent half a day on the official web saw

Mongodb://username:[email protected]:p ort/databasename

The model is written

Nothing else, but note the ID, the type of time, using the Mongdodb own data type

A virtual function is used here to make it easy for helper to get ID in generic type

The following is the model source code

Using system;using system.collections.generic;using system.linq;using system.text;using MongoDB.Driver;using Mongodb.bson;namespace windowsformsapplication1.model{Public    abstract class Mongomodel    {         public ObjectId ID {get; set;}         Public Bsondatetime created_at {get; set;}        Public Bsondatetime updated_at {get; set;}     } public class Accountmodel:mongomodel    {
Example public Accountmodel () { } public string name {get; set;}} }

Helper Writing

Because MongoDB's operation statements must be heavily used in your model, consider generics for helper

The reason for using the builder mode is that you can modify the code to initialize directly with the constructor function.

I also do not use static methods, you have to be able to modify their own

The following is the helper source code

Using system;using system.collections.generic;using system.linq;using system.text;using System.IO;using System.Xml; Using system.xml.serialization;using mongodb.driver;using mongodb.bson;using mongodb.driver.builders;namespace framework{public class mongohelper<t> where T:windowsformsapplication1.model.mongomodel {public str        ing Conn;        public string DbName;        public string CollectionName;        Private Mongocollection<t> collection;        Private Mongohelper () {}//<summary>//Set your collection//</summary>            public void Setcollection () {mongoclient client = new Mongoclient (conn); var server = client.            Getserver (); var database = server.            Getdatabase (DbName); Collection = database.        Getcollection<t> (CollectionName);    }///<summary>///When you use LINQ,///</summary> public void GetCollection ()    {mongoclient client = new Mongoclient (conn); var server = client.            Getserver (); var database = server.            Getdatabase (DbName); Collection = database.        Getcollection<t> (CollectionName);         }///<summary>//Find//</summary>//<param name= "Query" ></param> <returns></returns> public T Find (imongoquery query) {return This.collec tion.        FindOne (query); }/** * Conditional query with LINQ * http://mongodb.github.io/mongo-csharp-driver/1.11/linq/* */Pub Lic list<t> FindAll () {return this.collection.FindAll ().        ToList ();         }//<summary>//Modify//</summary>//<param name= "model" ></param> <returns></returns> Public long Update (T model) {Bsondocument doc = Bson Extensionmethods.tobsondoCument (model);            Writeconcernresult res = this.collection.Update (Query.eq ("_id", Model.id), New UpdateDocument (DOC)); return Res.        documentsaffected;         }///<summary>//Add//</summary>//<param name= "model" ></param> <returns></returns> public bool Insert (T model) {Writeconcernresult res            = This.collection.Insert (model); return Res.        Ok;         }///<summary>//delete//</summary>//<param name= "model" ></param> <returns></returns> public bool Delete (T model) {Writeconcernresult res            = This.collection.Remove (Query.eq ("_id", model.id)); return Res.        Ok; }///<summary>//constructor///</summary>//<typeparam name= "T" ></typepara M> public class builder<t> where t:windowsforMsApplication1.Model.MongoModel {private mongohelper<t> client;            Public Builder () {client = new mongohelper<t> ();            } public void Setconn (string conn) {client.conn = conn;            } public void Setdbname (string dbName) {client.dbname = DbName; } public void Setcollectionname (string collectionname) {client.collectionname = coll            Ectionname; Public mongohelper<t> Build () {client.                Setcollection ();            return client; }        }    }}

Use of Helper

Very simple, I wrote in the demo's form code, the note also written clearly what the process

1. Design your model

2. Initializing the database configuration

3.build a Helper

4. Calling methods

Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.text;using system.windows.forms;using devcomponents.dotnetbar;using system.io;using FrameWork;     Namespace windowsformsapplication1{/** * * MongoDB database additions and Deletions change the demo * Any copy, modify * for learning only * Zeng Weizhou 16/2/25    * * App Independent Development Group 533838427 * * */public partial class MainForm:DevComponents.DotNetBar.Metro.MetroForm        {public Model.confmodel conf = new Model.confmodel ();        private bool IsFirst = true;        private string FilePath;        Private list<model.accountmodel> accounts = new list<model.accountmodel> ();        Private framework.mongohelper<model.accountmodel> client;            Public MainForm () {InitializeComponent (); This.        Activated + = new EventHandler (form2_activated);           } void Form2_activated (object sender, EventArgs e) {if (IsFirst) {init ();            IsFirst = false;             }} void Init () {/** * * step-1 * Configure your MongoDB link        * Please complete the configuration * * */conf.mongodb_dbaddr = "localhost"; private void Buttonx2_click (object sender, EventArgs e) {/** * * step -2 * Please modify your model before operation * * step-3 * Initialize a helper with builder * Of course you are completely You can modify the code to initialize directly inside the constructor * I think it's fun. * * * * * * FRAMEWORK.MONGOHELPER&LT;MODEL.ACCOUNTM Odel>. builder<model.accountmodel> builder = new Framework.mongohelper<model.accountmodel>.            Builder<model.accountmodel> ();            Builder.setcollectionname ("Your collection name");            Builder.setconn (Conf.mongodb_conn);            Builder.setdbname (Conf.mongodb_dbname);        Client = Builder.build ();  }      private void Buttonx1_click (object sender, EventArgs e) {//Add Model.accountmodel Accoun            t = new Model.accountmodel ();            Account.name = "Love"; Client.            Insert (account); Delete the client.            Delete (account);            Change account.name = "Not Love"; Client.            Update (account); Check Model.accountmodel res = client. Find (MONGODB.DRIVER.BUILDERS.QUERY&LT;MODEL.ACCOUNTMODEL&GT;.            EQ (xx = xx.id, account.id)); Query operations with LINQ are strongly recommended//http://mongodb.github.io/mongo-csharp-driver/1.11/linq///var query = Collectio N.asqueryable<model.accountmodel> ().        Where (E = = E.firstname = = "John"); }    }}

Resources

http://mongodb.github.io/mongo-csharp-driver/1.11/linq/

http://blog.csdn.net/haukwong/article/details/7840158

Http://www.cnblogs.com/viprx/archive/2012/09/07/2674637.html

Demo download

Link: Http://pan.baidu.com/s/1qX3vfdE Password: buh2

Manipulating MongoDB with C # (demo included)

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.