MongoDB C # Driver (driver) Introduction and curd

Source: Internet
Author: User
Tags httpcontext mongoclient return tag

MongoDB C # Driver (driver) Introduction

There are currently two types of MongoDB drivers based on C #, namely the official drive () and the Samus driver ().
This time we only demonstrate the official drive usage.
Official Drive Document View

First step: referencing the driver DLL

There are two ways to refer to drivers:
1. Download the corresponding version according to the above, and then refer to the project.
2. On the project's reference, right-click the Manage NuGet package (first ensure that NuGet expansion pack is installed), online search official driver DLL (search condition is "official MongoDB"), and the installation will refer to 3 DLLs when installed successfully ( Mongodb.driver and Mongodb.bson,newtonsoft.json).

Step two: Construct the Mongodbhelper class

The code is as follows:

Using mongodb.driver;using system;using system.collections.generic;using system.linq;using System.Text;using System.threading.tasks;namespace server.dal.dbhelper{public sealed class Mongodbhelper {static public Reado        nly mongodbhelper Instance = new Mongodbhelper ();        Private Mongodatabase DB; Private Mongodbhelper () {//http://www.studyofnet.com/news/337.html//mongodb://[username:[em ail protected]]host1[:p ort1][,host2[:p Ort2],... [, hostn[:p Ortn]]            [/[database][?options]] string strconn = "mongodb://sa:[email protected]:27017";            String dbName = "Test";            MongoDB.Driver.MongoClient mongoclient = new Mongoclient (strconn);            Mongoserver Server = Mongoclient.getserver (); db = Server.        Getdatabase (DbName);        Public Mongodatabase db {get {return DB;}      } public mongocollection this[string value] {get {          Return DB.            GetCollection (value); }        }     }}
Step three: Add entity objects

Here is a complex person object with the following code:

 public class Test:BaseEntity{}public class PersonType : BaseEntity{    public string Code { get; set; }    public string Display { get; set; }}public class Person : BaseEntity{    //如果对应多个分类,则格式为:,3,34,2    public string PersonType { get; set; }    public string Name { get; set; }    public bool Sex { get; set; }    public int Age { get; set; }    public DateTime AddTime { get; set; }    public List<Address> Addresses { get; set; }    public List<string> Courses { get; set; }}public class Address{    public string Province { get; set; }    public string City { get; set; }}

BaseEntity description

BaseEntity is the auto-generated _id (type Objectid) in the MongoDB database.

 public class BaseEntity{    /// <summary>    /// 字段映射,告诉mongodb这个字段在数据库中对应_id    /// </summary>    [BsonId]    //告诉mongodb这个字段在数据库中的类型是ObjectId    [BsonRepresentation(BsonType.ObjectId)]    public string _id { get; set; }}
Fourth Step: Create Apicontroller

Create Apicontroller base class Baseapicontroller

Some variables are initialized in Baseapicontroller, and the code is as follows:

  public class Baseapicontroller:apicontroller {public int skip, take;        public Mongodatabase DB;                      Public mongocollection col = null;//The JSON public Baseapicontroller (string collectionname) used to return the query directly {            Skip = Getintrequest ("Skip");            Take = Getintrequest ("Take"); if (skip = = 0 && take = = 0) {take = Int.            MaxValue;            } db = Server.DAL.DBHelper.MongodbHelper.Instance.DB; Col = db.        GetCollection (CollectionName); public string Getstringrequest (string paramter) {return HttpContext.Current.Request.QueryStrin G[paramter]??        ""; } public int Getintrequest (string paramter) {string tmp = HttpContext.Current.Request.QueryStrin G[paramter]??            "";            int tag = 0; Int.            TryParse (tmp, out tag);        return tag; }    }   

Create TestController Inheritance Baseapicontroller

We'll use TestController to demonstrate curd.
The specific code is as follows, no longer detailed description:

public class testcontroller:filter.baseapicontroller{Public TestController (): Base ("person") {} PU Blic string Post ([Frombody]object value) {var model = jsonconvert.deserializeobject<person> (VA Lue.        ToString ()); model._id = Objectid.generatenewid ().        ToString (); try {Col.            Insert (model);        return model._id;        } catch (WebException ex) {throw ex; }} public Object Get () {try {ienumerable<person> queryable = col.            Asqueryable<person> ();            Func<person, bool> where = null;            How many conditions and how many conditions//like//var name = getstringrequest ("name"); if (!string.                IsNullOrEmpty (name)) {where = c = c.name.contains (name); queryable = queryable.            where (where); }//Single condition equivalent query var persontype = getstringrequest("PersonType"); if (!string.                IsNullOrEmpty (PersonType)) {where = c = C.persontype = = PersonType; queryable = queryable.            where (where);            }//nested arrays query var course = getstringrequest ("course"); if (!string.                IsNullOrEmpty (course)) {where = c = C.courses.contains (course); queryable = queryable.            where (where);            }//Nested entity Collection Query---number of var address = Getstringrequest ("Address"); if (!string.                IsNullOrEmpty (address)) {where = c = c.addresses.count > Getintrequest ("Address"); queryable = queryable.            where (where); } var personlist = queryable. OrderByDescending (c = c._id). Skip (Skip). Take (take).            ToList (); var count = queryable.            Count ();            var data = new {count = count, dataList = personlist};        return data; } catch (WebException ex)        {Throw ex; }} public person Get (string id) {try {var model = Col. Asqueryable<person> ().            FirstOrDefault (c = c._id = = ID);        return model;        } catch (WebException ex) {throw ex; }}//Part of the field modifies the mode, only the fields that need to be modified are modified.                           The disadvantage is that only a single property can be modified, and the public int Put (string ID, [frombody]object value) {try {) cannot be modified for nested arrays and nested entity collections            var query = new Querydocument {"_id", Objectid.parse (ID)}}; var dicdata = jsonconvert.deserializeobject<dictionary<string, object>> (value.            ToString ());            var update = new UpdateDocument {"$set", New Querydocument (Dicdata)}}; Col.            Update (query, update);        return 1;        } catch (WebException ex) {throw ex; }}//Full modification mode, first check and change, support any type of object modification.    The disadvantage is that you need to first query the public int Put ([frombody]object value) {try {        var model = jsonconvert.deserializeobject<person> (value.            ToString ()); Col.            Save (model);        return 1;        } catch (WebException ex) {throw ex; }} public void Delete (string id) {try {var query = new Querydocument {"_id", objec            Tid.parse (ID)}}; Col.                      Remove (query);        } catch (WebException ex) {throw ex; }    }}
Fifth Step: Curd Demo

Here we use a tool Fiddler2 demo.

Add to

MongoDB C # Driver (driver) Introduction and curd

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.