C # operating Mongodb,

Source: Internet
Author: User

C # operating Mongodb,

Because MongoDb is cross-platform, it can be used for free, with high read/write efficiency, simple cluster construction, horizontal scaling, and other factors.

I decided to study Mongodb. After reading the relevant documentation, I found that it has good support for C # And there is also a ready-made C # driver,

The new version of the driver also supports Linq, because complicated queries can be implemented by Linq. This is because the official driver is very powerful.

At the beginning, I found a lot of things to understand. In order to quickly handle simple projects, I further encapsulated the official driver. The official dll must be introduced in the project,

Https://github-cloud.s3.amazonaws.com/releases/699689/ea9bea12-819f-11e6-965b-d3b6bb718019.zip? Response & response-content-type = application % 2Foctet-stream

After the download, decompress the package to the corresponding directory and introduce the dll to the project (as shown in the red box)

 


The following are some simple addition, deletion, modification, and query operations encapsulated by Alibaba Cloud.

1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. text; 5 using System. threading. tasks; 6 using MongoDB. driver; 7 using MongoDB. bson; 8 using MongoDB. bson. serialization. attributes; 9 using System. linq. expressions; 10 11 namespace Langu. dbHelper 12 {13 /// <summary> 14 /// MongoDb database operation class 15 /// </summary> 16 public class operation helper <T> where T: baseEntity 17 {18 /// <summary> 19 // database object 20 /// </summary> 21 private IMongoDatabase database; 22 /// <summary> 23 // constructor 24 /// </summary> 25 /// <param name = "conString"> connection string </param> 26 public writable helper (String conString) 27 {28 var url = new response url (conString); 29 Response clientsettings mcs = Response clientsettings. fromUrl (url); 30 mcs. maxConnectionLifeTime = TimeSpan. fromMilliseconds (1000); 31 var client = new Alibaba client (mcs); 32 this. database = client. getDatabase (url. databaseName ); 33} 34 // <summary> 35 // create a collection object 36 // </summary> 37 // <param name = "collName"> set name </ param> 38 // <returns> collection object </returns> 39 private IMongoCollection <T> GetColletion (String collName) 40 {41 return database. getCollection <T> (collName ); 42} 43 44 # add region 45 // <summary> 46 // insert object 47 /// </summary> 48 /// <param name = "collName"> set name </param> 49 // <param name = "t"> inserted object </param> 50 public void Insert (String collName, T t) 51 {52 var coll = GetColletion (collName); 53 coll. insertOne (t ); 54} 55 // <summary> 56 // batch insert 57 // </summary> 58 // <param name = "collName"> set name </param> 59 // <param name = "ts"> set of objects to be inserted </param> 60 public void InsertBath (String collName, IEnumerable <T> ts) 61 {62 var coll = GetColletion (collName); 63 coll. insertts (ts ); 64} 65 # endregion 66 67 # region Delete 68 // <summary> 69 // Delete 70 according to the condition of BsonDocument /// </summary> 71 // <param name = "collName"> set name </param> 72 // <param name = "document"> document </param> 73 // <returns> </returns> 74 public Int64 Delete (String collName, bsonDocument document) 75 {76 var coll = GetColletion (collName); 77 var result = coll. deleteOne (document); 78 return result. deletedCount; 79} 80 // <summary> 81 // Delete 82 by json string // </summary> 83 // <param name = "collName"> set name </param> 84 // <param name = "json"> json String </param> 85 // <returns> </returns> 86 public Int64 Delete (String collName, string json) 87 {88 var coll = GetColletion (collName); 89 var result = coll. deleteOne (json); 90 return result. deletedCount; 91} 92 // <summary> 93 // Delete 94 by conditional expression // </summary> 95 // <param name = "collName"> set name </param> 96 // <param name = "predicate"> conditional expression </param> 97 // <returns> </returns> 98 public Int64 Delete (String collName, expression <Func <T, Boolean> predicate) 99 {100 var coll = GetColletion (collName); 101 var result = coll. deleteOne (predicate); 102 return result. deletedCount; 103} 104 // <summary> 105 // Delete 106 Based on search conditions // we recommend that you use Builders <T> to construct a complex query condition 107 // </summary> 108 // <param name = "collName"> set name </param> 109 // <param name = "filter"> condition </param> 110 // <returns> </returns> 111 public Int64 Delete (String collName, filterDefinition <T> filter) 112 {113 var coll = GetColletion (collName); 114 var result = coll. deleteOne (filter); 115 return result. deletedCount; 116} 117 # endregion118 119 # modify region 120 // <summary> 121 // modify document 122 /// </summary> 123 // <param name = "collName "> set name </param> 124 // <param name =" filter "> modify condition </param> 125 // <param name =" update "> modify result </param> 126 // <param name = "upsert"> whether to insert a new document (update if the filter condition is met, otherwise, insert a new document.) </param> 127 // <returns> </returns> 128 public Int64 Update (String collName, Expression <Func <T, Boolean> filter, updateDefinition <T> update, Boolean upsert = false) 129 {130 var coll = GetColletion (collName); 131 var result = coll. updateMany (filter, update, new UpdateOptions {IsUpsert = upsert}); 132 return result. modifiedCount; 133} 134 // <summary> 135 // Replace the new document with the new object 136 // </summary> 137 // <param name = "collName"> set name </param> 138 /// <param name = "filter"> modify condition </param> 139 /// <param name = "t"> new object </param> 140 // <param name = "upsert"> whether to insert a new document (update if the filter condition is met, otherwise, insert a new document) </param> 141 // <returns> modify the number of affected documents </returns> 142 public Int64 Update (String collName, Expression <Func <T, boolean> filter, T, Boolean upsert = false) 143 {144 var coll = GetColletion (collName); 145 BsonDocument document = t. toBsonDocument <T> (); 146 document. remove ("_ id"); 147 UpdateDocument update = new UpdateDocument ("$ set", document); 148 var result = coll. updateMany (filter, update, new UpdateOptions {IsUpsert = upsert}); 149 return result. modifiedCount; 150} 151 # endregion152 153 // <summary> 154 // query, for complex queries, process 155 // </summary> 156 // <param name = "collName"> set name </param> 157 // <returns> the queried object </returns> 158 public IQueryable <T> GetQueryable (String collName) 159 {160 var coll = GetColletion (collName); 161 return coll. asQueryable <T> (); 162} 163 # region Query 164 # endregion165} 166 167 // <summary> 168 // entity base class, easy to generate _ id169 // </summary> 170 public class BaseEntity171 {172 [BsonRepresentation (BsonType. objectId)] 173 public String Id {get; set;} 174 // <summary> 175 // give the initial value of the object 176 /// </summary> 177 public BaseEntity () 178 {179 this. id = ObjectId. generateNewId (). toString (); 180} 181} 182}

A simple console call was made (provided that the mongodb service has been opened, Mongodb is installed, and some of the time to be opened will be sent together)

 

1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. text; 5 using System. threading. tasks; 6 using Langu. dbHelper; 7 using System. threading; 8 using System. linq. expressions; 9 using MongoDB. driver; 10 11 namespace Client12 {13 class Program14 {15 static void Main (string [] args) 16 {17 // connection String 127.0.0.1 Server IP 27100 mongodb service port number mydb database name 18 String conString = "mongodb: // 127.0.0.1: 27100/mydb "; 19 // instantiate the Helper Object (generic version). The constructor requires that 20 rows Helper be passed in as the connection string <User> begin helper = new rows helper <User> (conString ); 21 // query the amount of data in the Set user 22 var cnt = login helper. getQueryable ("user "). count (); 23 Console. writeLine (cnt); 24 Console. readKey (); 25} 26} 27 28 internal class User: BaseEntity29 {30 public int Age {get; set ;}31 public String Name {get; set ;}32} 33}

 

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.