8-Day Learning mongodb--Eighth Day Drive practice

Source: Internet
Author: User

As the last article in the series, we have to say that C # drives the operation of MongoDB, there are two types of drivers: official drive and Samus Drive, but I personally prefer the latter.

Because it provides rich LINQ operations, it's quite handy.

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.

The following is a concrete look at the Samus drive, Https://github.com/samus/mongodb-csharp/blob/master/examples/Simple/Main.cs above provides

A simple demo, in general we'll know how to play.

One: Practice

1: We create a person entity, the Mongoalias attribute represents the alias, where the ID value will overwrite the database automatically generated _id.

1 #region Data Entities
2// <summary>
3//Data entity
4//</summary>
5 Public class person
6 {
7 [Mongoalias ("_id")]
8 public string ID {get; set;}

Ten public string Name {get; set;}

Public int Age {get; set;}

Public DateTime Createtime {get; set;}
}
#endregion


2: Initialize a number of variables

1         String connectionString = string. Empty;

3 String databaseName = string. Empty;

5 String collectionname = string. Empty;

7 static mongodbhelper<t> MongoDB;

9 #region Initialization operation
<summary>
11///Initialize operation
</summary>
Public Mongodbhelper ()
{
connectionString = "server=127.0.0.1:2222";
databaseName = "Shopex";
CollectionName = "person";
(+ }
#endregion

3: In order to facilitate the inheritance class of T using the LINQ feature, we also need to map a bit.

1 #region Mapping configuration for LINQ queries
2// <summary>
3///Map configuration to implement LINQ queries
4//</summary>
5 Public mongoconfiguration Configuration
6 {
7 Get
8 {
9 var config = new Mongoconfigurationbuilder ();

CONFIG. Mapping (Mapping =
{
mapping. DefaultProfile (profile =
{
Profile . Subclassesare (t = t.issubclassof (typeof (T)));
);
mapping. Map<t> ();
mapping. Map<t> ();
});

CONFIG. ConnectionString (ConnectionString);

The return CONFIG. Buildconfiguration ();
+ }
+ }
#endregion

4: Here are some basic curd code, similar to writing EF code, and very comfortable to write.

1 #region Insert operation
2//<summary>
3///insert operation
4//</summary>
5//<param name= "Person" ></param>
6//<returns></returns>
7 public void Insert (T t)
8 {
9 using (Mongo Mongo = new Mongo (configuration))
10 {
One-try
12 {
Mongo. Connect ();
14
The var db = Mongo. Getdatabase (DatabaseName);
16
The var collection = db. Getcollection<t> (CollectionName);
18
Collection. Insert (T, true);
20
Mongo. Disconnect ();
22
23}
catch (Exception)
25 {
Mongo. Disconnect ();
a throw;
28}
29}
30}
#endregion
32
#region Update operation
<summary>
35//Update operation
</summary>
Panax Notoginseng//<param name= "Person" ></param>
<returns></returns>
$ public void Update (T T, Expression<func<t, bool>> Func)
40 {
The using (Mongo Mongo = new Mongo (configuration))
42 {
Try
44 {
Mongo. Connect ();
46
var db = Mongo. Getdatabase (DatabaseName);
48
The var collection = db. Getcollection<t> (CollectionName);
50
Wuyi collection. Update<t> (T, Func, True);
52
Mongo. Disconnect ();
54
55}
Exception catch ()
57 {
Mongo. Disconnect ();
(a) a throw;
60}
61}
62}
#endregion
64
#region Get Collection
<summary>
67///Get Collection
</summary>
<param name= "Person" ></param>
<returns></returns>
list<t> List (int pageIndex, int pageSize, expression<func<t, bool>> Func, out int page Count)
72 {
PageCount = 0;
74
using (Mongo Mongo = new Mongo (configuration))
76 {
The Try
78 {
Mongo. Connect ();
80
Bayi var db = Mongo. Getdatabase (DatabaseName);
82
The collection var = db. Getcollection<t> (CollectionName);
84
PageCount = Convert.ToInt32 (collection. Count ());
86
personlist var = collection. Linq (). Where (func). Skip (PageSize * (pageIndex-1))
88. Take (pageSize). Select (i = i). ToList ();
89
Mongo. Disconnect ();
91
Personlist return;
93
94}
Exception catch ()
96 {
Mongo. Disconnect ();
98 throw;
99}
100}
101}
102 #endregion
103
104 #region Reading a single record
<summary>
106//Read a single record
107//</summary>
108//<param name= "Person" ></param>
109//<returns></returns>
-Public T (expression<func<t, bool>> Func)
111 {
Using the Mongo Mongo = new Mongo (configuration)
113 {
Try
115 {
Mongo. Connect ();
117
118 var db = Mongo. Getdatabase (DatabaseName);
119
The var collection = db. Getcollection<t> (CollectionName);
121
122 var single = collection. Linq (). FirstOrDefault (func);
123
124 MONGO. Disconnect ();
125
126 return single;
127
128}
129 catch (Exception)
130 {
131 MONGO. Disconnect ();
;
133}
134}
135}
136 #endregion
137
138 #region Delete operation
139//<summary>
140///delete operation
141//</summary>
142//<param name= "Person" ></param>
143//<returns></returns>
144 public void Delete (expression<func<t, bool>> Func)
145 {
146 using (Mongo Mongo = new Mongo (configuration))
147 {
148 Try
149 {
Mongo. Connect ();
151
var db = Mongo. Getdatabase (DatabaseName);
153
154 var collection = db. Getcollection<t> (CollectionName);
155
156//This place should be noted that the T parameter must be added, otherwise it will be treated as Object type
157//causes deletion to fail
158 collection. Remove<t> (func);
159
Mongo. Disconnect ();
161
162}
163 catch (Exception)
164 {
165 MONGO. Disconnect ();
166 throw;
167}
168}
169}
#endregion



5. OK, let's open the 2222 port, because the previous article I have made this MongoDB service, now directly connected to the past, and do a name index.

6. Everything is ready, we do basic operations, such as here I add 1000 data, note that I opened the safe mode, if the insertion is unsuccessful, will throw an exception.

<1> ADD:

1    static void Main (string[] args)
2 {
3 mongodbhelper<person> helper = new mongodbhelper<person> ();

5 //INSERT 1000 data
6 for (int i = 0; i <; i++)
7 {
8 Helper. Insert (New Person ()
9 {
Ten ID = Guid.NewGuid (). ToString (),
One Name = "Jack" + I,
Age = i,
Createtime = DateTime.Now
);
}

Console.WriteLine ("Insert Success");

Console.read ();
( }

At first glance the data displayed is problematic, why there is no jack0 or jack999, but the find after a bit of a comfortable mood.

<2> update: Get rid of jack941 's name "Mary"

1  static void Main (string[] args)
2 {
3 mongodbhelper<person> helper = new mongodbhelper<person> ();

5 //change jack941 to Mary
6 var single = helper. Single (i = I.name = = "jack941");
7 single . Name = "Mary";
8 Helper. Update (single, i = I.id = = single.id);

Console.WriteLine ("Modified successfully");
Console.read ();
-- }

<3>delete: Delete Mary's record

1      static void Main (string[] args)
2 {
3 mongodbhelper<person> helper = new mongodbhelper<person> ();

5 //delete Mary this record
6 Helper. Delete (i = I.name = = "Mary");

8 Console.WriteLine ("Delete succeeded");
9 console.read ();
Ten }


<4> list operations: Here I get a list of 9 people in the name.

1    static void Main (string[] args)
2 {
3 mongodbhelper<person> helper = new mongodbhelper<person> ();

5 int PageCount;

7 //Get the number of people with 9 in the name
8 var list = helper. List (1, +, I = I.name.contains ("9"), out PageCount);

Ten console.read ();
One }

The total running code

Using system;using system.collections.generic;using system.linq;using system.text;using System.Configuration;using System.linq.expressions;using mongodb.configuration;using mongodb.linq;using Mongodb.attributes;namespace mongodb.test{public class mongodbhelper<t> where T:class {string connectionString = string.        Empty; String databaseName = String.        Empty; String CollectionName = String.        Empty;        Static mongodbhelper<t> MongoDB; #region initialization operation///<summary>///initialization operation///</summary> public Mongodbhelper () {Co            nnectionstring = "server=127.0.0.1:2222";            DatabaseName = "Shopex";        CollectionName = "Person"; #endregion #region Map configuration to implement LINQ queries//<summary>///implement a mapping configuration for LINQ queries///</summary> PU Blic mongoconfiguration Configuration {get {var config = new Mongoconfigurat               Ionbuilder (); Config. Mapping (Mapping = {Mapping. DefaultProfile (profile =.                    Subclassesare (t = t.issubclassof (typeof (T)));                    }); Mapping.                    Map<t> (); Mapping.                Map<t> ();                }); Config.                ConnectionString (ConnectionString); return CONFIG.            Buildconfiguration (); }} #endregion #region insert operation///<summary>///Insert operation///</summary>///<param name= ' Person ' ></param>///<returns></returns> public void Insert (T t) {using (Mo NGO MONGO = new MONGO (configuration)) {try {MONGO.                    Connect (); var db = Mongo.                    Getdatabase (DatabaseName); var collection = db.                    Getcollection<t> (CollectionName); Collection. Insert (T,true); Mongo.                Disconnect (); } catch (Exception) {MONGO.                    Disconnect ();                Throw }}} #endregion #region Update operation///<summary>///Update operation///</summary>///&L T;param name= ' person ' ></param>///<returns></returns> public void Update (T T, Expression<fu                Nc<t, bool>> func) {using (Mongo Mongo = new Mongo (configuration)) { try {MONGO.                    Connect (); var db = Mongo.                    Getdatabase (DatabaseName); var collection = db.                    Getcollection<t> (CollectionName); Collection.                    Update<t> (T, Func, True); Mongo.                Disconnect (); } catch (Exception) {MONGO.                    Disconnect ();           Throw     }}} #endregion #region get collection//<summary>///Get collection//</summary>// /<param name= ' person ' ></param>///<returns></returns> public list<t> List (int pagein            Dex, int pageSize, expression<func<t, bool>> Func, out int pagecount) {PageCount = 0;                    using (Mongo Mongo = new Mongo (configuration)) {try { Mongo.                    Connect (); var db = Mongo.                    Getdatabase (DatabaseName); var collection = db.                    Getcollection<t> (CollectionName); PageCount = Convert.ToInt32 (collection.                    Count ()); var personlist = collection. Linq (). Where (func). Skip (PageSize * (pageIndex-1)). Take (pageSize). Select (i = i).                    ToList (); Mongo.                    Disconnect ();                return personlist;  }              catch (Exception) {MONGO.                    Disconnect ();                Throw  }}} #endregion #region read a single record///<summary>///read a single record///</summary>/// <param name= ' person ' ></param>///<returns></returns> public T (expression<func&lt ;                T, bool>> func) {using (Mongo Mongo = new Mongo (configuration)) {try {MONGO.                    Connect (); var db = Mongo.                    Getdatabase (DatabaseName); var collection = db.                    Getcollection<t> (CollectionName); var single = collection. Linq ().                    FirstOrDefault (func); Mongo.                    Disconnect ();                return single; } catch (Exception) {MONGO.                    Disconnect ();                Throw      }            }  } #endregion #region Delete operation//<summary>///delete operation///</summary>///<param name= "person "></param>///<returns></returns> public void Delete (Expression<func<t, bool>> fun                    c) {using (Mongo Mongo = new Mongo (configuration)) {try { Mongo.                    Connect (); var db = Mongo.                    Getdatabase (DatabaseName); var collection = db.                    Getcollection<t> (CollectionName); This place should be noted that the T parameter must be added, otherwise it will be treated as an object type//cause the deletion to fail collection.                    Remove<t> (func); Mongo.                Disconnect (); } catch (Exception) {MONGO.                    Disconnect ();                Throw }}} #endregion} #region Data Entities///<summary>///data Entities///</summary> Publi C class Person {[Mongoalias("_id")]        public string ID {get; set;}        public string Name {get; set;}        public int Age {get; set;}    Public DateTime createtime {get; set;} } #endregion}

  

Taking advantage of 3 days of vacation, continuous efforts to finally finish this series, thank you have been concerned about this series of friends.

8-Day Learning mongodb--Eighth Day Drive 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.