The MongoDbCsharpHelper class (CRUD class) is encapsulated based on the official MongoDb C # driver ),

The MongoDbCsharpHelper class (CRUD class) is encapsulated based on the official MongoDb C # driver ),

Source: Internet
Author: User
Tags createindex

The MongoDbCsharpHelper class (CRUD class) is encapsulated based on the official MongoDb C # driver ),

MongoDb is used as a log persistence object in recent work. MongoDb needs to be added, deleted, modified, and queried. However, because MongoDb is of a newer version, it is of version 2.4 or later, some of the existing MongoDb Helper classes on the Internet are based on old MongoDb versions and cannot be applied to new MongoDb versions. Therefore, I re-encapsulated the MongoDbCsharpHelper class (CRUD class) based on the official MongoDb C # driver ), the complete code is as follows:

Using MongoDB; using MongoDB. bson; using MongoDB. driver; using System. collections; using System. collections. generic; using System. linq; using System. linq. expressions; using System. reflection; using System. threading; using System. web; namespace Zuowj. utils {// <summary> // MongoDbCsharpHelper: MongoDb C # language-based operation help class // Author: Zuowenjun // Date: // </summary> public class MongoDbCsharpHe Lper {private readonly string connectionString = null; private readonly string databaseName = null; private MongoDB. driver. IMongoDatabase database = null; private readonly bool autoCreateDb = false; private readonly bool autoCreateCollection = false; static MongoDbCsharpHelper () {BsonDefaults. guidRepresentation = GuidRepresentation. standard;} public comment dbcsharphelper (string comment connstr, stri Ng dbName, bool autoCreateDb = false, bool autoCreateCollection = false) {this. connectionString = Response connstr; this. databaseName = dbName; this. autoCreateDb = autoCreateDb; this. autoCreateCollection = autoCreateCollection;} # region private method private jsonclient CreateMongoClient () {return new jsonclient (connectionString);} private MongoDB. driver. IMongoDatabase getaskdatabase () {if (database = Null) {var client = CreateMongoClient (); if (! DatabaseExists (client, databaseName )&&! AutoCreateDb) {throw new KeyNotFoundException ("This MongoDB name does not exist:" + databaseName);} database = CreateMongoClient (). getDatabase (databaseName);} return database;} private bool DatabaseExists (LOGIN client, string dbName) {try {var dbNames = client. listDatabases (). toList (). select (db => db. getValue ("name "). asString); return dbNames. contains (dbName);} catch // If the connected account cannot enumerate all databases, an error is returned, and the default value is true {retu Rn true ;}} private bool CollectionExists (IMongoDatabase database, string collectionName) {var options = new ListCollectionsOptions {Filter = Builders <BsonDocument>. filter. eq ("name", collectionName)}; return database. listCollections (options ). toEnumerable (). any ();} private MongoDB. driver. IMongoCollection <TDoc> getaskcollection <TDoc> (string name, colleccollectionsettings settings = null) {var Foreign database = getforeign database (); if (! CollectionExists (relational database, name )&&! AutoCreateCollection) {throw new KeyNotFoundException ("this Collection name does not exist:" + name);} return duplicate database. getCollection <TDoc> (name, settings);} private List <UpdateDefinition <TDoc> BuildUpdateDefinition <TDoc> (object doc, string parent) {var updateList = new List <UpdateDefinition <TDoc> (); foreach (var property in typeof (TDoc ). getProperties (BindingFlags. instance | BindingFlags. public) {var key = Parent = null? Property. name: string. format ("{0 }. {1} ", parent, property. name); // non-null complex type if (property. propertyType. isClass | property. propertyType. isInterface) & property. propertyType! = Typeof (string) & property. GetValue (doc )! = Null) {if (typeof (IList ). isAssignableFrom (property. propertyType) {# region set type int I = 0; var subObj = property. getValue (doc); foreach (var item in subObj as IList) {if (item. getType (). isClass | item. getType (). isInterface) {updateList. addRange (BuildUpdateDefinition <TDoc> (doc, string. format ("{0 }. {1} ", key, I);} else {updateList. add (Builders <TDoc>. update. set (string. format ("{0 }. {1} ", key, I), item) ;} I ++ ;}# endregion} else {# region object type // complex type, navigation attribute, Class Object and collection object var subObj = property. getValue (doc); foreach (var sub in property. propertyType. getProperties (BindingFlags. instance | BindingFlags. public) {updateList. add (Builders <TDoc>. update. set (string. format ("{0 }. {1} ", key, sub. name), sub. getValue (subObj) ;}# endregion }} else // simple type {updateList. add (Builders <TDoc>. update. set (key, p Roperty. getValue (doc);} return updateList;} private void CreateIndex <TDoc> (IMongoCollection <TDoc> col, string [] indexFields, CreateIndexOptions options = null) {if (indexFields = null) {return;} var indexKeys = Builders <TDoc>. indexKeys; IndexKeysDefinition <TDoc> keys = null; if (indexFields. length> 0) {keys = indexKeys. descending (indexFields [0]);} for (var I = 1; I <indexFields. lengt H; I ++) {var strIndex = indexFields [I]; keys = keys. Descending (strIndex);} if (keys! = Null) {col. indexes. createOne (keys, options) ;}# endregion public void CreateCollectionIndex <TDoc> (string collectionName, string [] indexFields, CreateIndexOptions options = null) {CreateIndex (getaskcollection <TDoc> (collectionName), indexFields, options);} public void CreateCollection <TDoc> (string [] indexFields = null, CreateIndexOptions options = null) {string collectionName = typeof (TDoc). Name; CreateCollection <TDoc> (collectionName, indexFields, options);} public void CreateCollection <TDoc> (string collectionName, string [] indexFields = null, CreateIndexOptions options = null) {var foreign database = getforeign database (); foreign database. createCollection (collectionName); CreateIndex (GetMongoCollection <TDoc> (collectionName), indexFields, options);} public List <TDoc> Find <TDoc> (Expressio N <Func <TDoc, bool> filter, FindOptions options = null) {string collectionName = typeof (TDoc ). name; return Find <TDoc> (collectionName, filter, options);} public List <TDoc> Find <TDoc> (string collectionName, Expression <Func <TDoc, bool> filter, findOptions options = null) {var colleciton = getmediacollection <TDoc> (collectionName); return colleciton. find (filter, options ). toList ();} public List <TDo C> FindByPage <TDoc, TResult> (Expression <Func <TDoc, bool> filter, Expression <Func <TDoc, TResult> keySelector, int pageIndex, int pageSize, out int rsCount) {string collectionName = typeof (TDoc ). name; return FindByPage <TDoc, TResult> (collectionName, filter, keySelector, pageIndex, pageSize, out rsCount);} public List <TDoc> FindByPage <TDoc, TResult> (string collectionName, expression <Func <TDoc, bo Ol> filter, Expression <Func <TDoc, TResult> keySelector, int pageIndex, int pageSize, out int rsCount) {var colleciton = GetMongoCollection <TDoc> (collectionName ); rsCount = colleciton. asQueryable (). where (filter ). count (); int pageCount = rsCount/pageSize + (rsCount % pageSize)> 0? 1: 0); if (pageIndex> pageCount) pageIndex = pageCount; if (pageIndex <= 0) pageIndex = 1; return colleciton. asQueryable (new aggresponoptions {AllowDiskUse = true }). where (filter ). orderByDescending (keySelector ). skip (pageIndex-1) * pageSize ). take (pageSize ). toList ();} public void Insert <TDoc> (TDoc, InsertOneOptions options = null) {string collectionName = typeof (TDoc ). name; Insert <TDoc> (CollectionName, doc, options);} public void Insert <TDoc> (string collectionName, TDoc doc, InsertOneOptions options = null) {var colleciton = GetMongoCollection <TDoc> (collectionName); colleciton. insertOne (doc, options);} public void insertstrap <TDoc> (IEnumerable <TDoc> docs, InsertManyOptions options = null) {string collectionName = typeof (TDoc ). name; InsertMany <TDoc> (collectionName, docs, option S);} public void InsertMany <TDoc> (string collectionName, IEnumerable <TDoc> docs, InsertManyOptions options = null) {var colleciton = GetMongoCollection <TDoc> (collectionName); colleciton. insertMany (docs, options);} public void Update <TDoc> (TDoc, Expression <Func <TDoc, bool> filter, UpdateOptions options = null) {string collectionName = typeof (TDoc ). name; var colleciton = getaskcollection <TDoc> (collectionName); List <UpdateDefinition <TDoc> updateList = BuildUpdateDefinition <TDoc> (doc, null); colleciton. updateOne (filter, Builders <TDoc>. update. combine (updateList), options);} public void Update <TDoc> (string collectionName, TDoc doc, Expression <Func <TDoc, bool> filter, UpdateOptions options = null) {var colleciton = GetMongoCollection <TDoc> (collectionName); List <UpdateDefinition <TDo C> updateList = BuildUpdateDefinition <TDoc> (doc, null); colleciton. updateOne (filter, Builders <TDoc>. update. combine (updateList), options);} public void Update <TDoc> (TDoc, Expression <Func <TDoc, bool> filter, UpdateDefinition <TDoc> updateFields, updateOptions options = null) {string collectionName = typeof (TDoc ). name; Update <TDoc> (collectionName, doc, filter, updateFields, options);} public Void Update <TDoc> (string collectionName, TDoc doc, Expression <Func <TDoc, bool> filter, UpdateDefinition <TDoc> updateFields, UpdateOptions options = null) {var colleciton = GetMongoCollection <TDoc> (collectionName); colleciton. updateOne (filter, updateFields, options);} public void UpdateMany <TDoc> (TDoc doc, Expression <Func <TDoc, bool> filter, UpdateOptions options = null) {string collectionName = Typeof (TDoc ). name; UpdateMany <TDoc> (collectionName, doc, filter, options);} public void UpdateMany <TDoc> (string collectionName, TDoc doc, Expression <Func <TDoc, bool> filter, UpdateOptions options = null) {var colleciton = GetMongoCollection <TDoc> (collectionName); List <UpdateDefinition <TDoc> updateList = BuildUpdateDefinition <TDoc> (doc, null); colleciton. updateMany (filter, Builders <TDoc>. upd Ate. combine (updateList), options);} public void Delete <TDoc> (Expression <Func <TDoc, bool> filter, DeleteOptions options = null) {string collectionName = typeof (TDoc ). name; Delete <TDoc> (collectionName, filter, options);} public void Delete <TDoc> (string collectionName, Expression <Func <TDoc, bool> filter, deleteOptions = null) {var colleciton = GetMongoCollection <TDoc> (collectionName); c Olleciton. deleteOne (filter, options);} public void DeleteMany <TDoc> (Expression <Func <TDoc, bool> filter, DeleteOptions options = null) {string collectionName = typeof (TDoc ). name; DeleteMany <TDoc> (collectionName, filter, options);} public void DeleteMany <TDoc> (string collectionName, Expression <Func <TDoc, bool> filter, deleteOptions options = null) {var colleciton = getaskcollection <TDoc> (col LectionName); colleciton. deleteMany (filter, options);} public void ClearCollection <TDoc> (string collectionName) {var colleciton = GetMongoCollection <TDoc> (collectionName); var inddexs = colleciton. indexes. list (); List <IEnumerable <BsonDocument> docIndexs = new List <IEnumerable <BsonDocument> (); while (inddexs. moveNext () {docIndexs. add (inddexs. current);} var response database = getresponse database (); Using database. DropCollection (collectionName); if (! CollectionExists (relational database, collectionName) {CreateCollection <TDoc> (collectionName);} if (docIndexs. count> 0) {colleciton = your database. getCollection <TDoc> (collectionName); foreach (var index in docIndexs) {foreach (IndexKeysDefinition <TDoc> indexItem in index) {try {colleciton. indexes. createOne (indexItem) ;}catch {}}}}}}}

Briefly describe several special points in the above Code:

1. because the producer client. getDatabase obtains the database and Consumer Client. the GetCollection <TDoc> method used to obtain a document (also known as a table) has the following features: if the specified DB name or Collection name does not exist, it is directly created, however, sometimes it may be because the database name or Collection name is incorrectly written, leading to the mistaken creation of the database or Collection, which may cause unnecessary trouble, therefore, two private methods are encapsulated in the MongoDbCsharpHelper class: DatabaseExists (to determine whether the database exists, if the connected account does not have the permission to retrieve the database, an error may be reported, therefore, the Code directly returns true), CollectionExists (to determine whether the Collection exists );

2. I have reloaded two methods for each CRUD method. One is that you do not need to specify the Collection name, and the other is to specify the Collection name. Why? The reason is very simple, because sometimes the Collection structure is the same but different collections, TDoc is the same entity class, but collectionName is different;

3. when querying by page, if the Collection data volume is large, a similar error will be reported: exception: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. aborting operation. pass allowDiskUse: true. Based on the error message, we add the aggresponoptions object when querying large data volumes, such as colleciton. asQueryable (new aggresponoptions {AllowDiskUse = true })

4. ClearCollection clears all the data of the Collection. If the data volume of the Collection is very large, it may take a long time to directly use colleciton. DeleteMany. Is there any method similar to SQL SERVER's truncate table? After many discussions, it is a pity that we have not found a method of similar functions. Only the DropCollection method is used. The DropCollection method directly deletes the Collection, including all the data in the Collection, which is highly efficient, however, because it is a Drop object, the Collection does not exist. If it is accessed again, there may be a Collection error that does not exist. Is there a good solution? Of course, it is To DropCollection first and then CreateCollection, finally, don't forget to insert the original index into the newly created Collection, so as to implement the role of truncate to initialize the table. Of course, when creating an index, sometimes an error may be reported (for example: _ id). Because _ id is created by default, an error may occur when you create an index. Therefore, colleciton. indexes. I added try catch outside CreateOne. If an error is returned, it will be ignored.

5. createCollection (create Collection) and CreateCollectionIndex (create Collection index) because sometimes we need to explicitly create a Collection or create an index for an existing Collection, it is inconvenient to use shell commands, therefore, it is encapsulated here.

Example:

Var mongoDbHelper = new MongoDbCsharpHelper ("MongoDbConnectionString", "LogDB"); mongoDbHelper. createCollection <SysLogInfo> ("SysLog1", new [] {"LogDT"}); mongoDbHelper. find <SysLogInfo> ("SysLog1", t => t. level = "Info"); int rsCount = 0; mongoDbHelper. findByPage <SysLogInfo, SysLogInfo> ("SysLog1", t => t. level = "Info", t => t, out rsCount); mongoDbHelper. insert <SysLogInfo> ("SysLog1", new SysLogInfo {LogDT = DateTime. now, Level = "Info", Msg = "Test message"}); mongoDbHelper. update <SysLogInfo> ("SysLog1", new SysLogInfo {LogDT = DateTime. now, Level = "Error", Msg = "Test message 2"}, t => t. logDT = new DateTime (1900,1, 1); mongoDbHelper. delete <SysLogInfo> (t => t. level = "Info"); mongoDbHelper. clearCollection <SysLogInfo> ("SysLog1 ");
Related Article
Large-Scale Price Reduction
  • 59% Max. and 23% Avg.
  • Price Reduction for Core Products
  • Price Reduction in Multiple Regions
undefined. /
Connect with us on Discord
  • Secure, anonymous group chat without disturbance
  • Stay updated on campaigns, new products, and more
  • Support for all your questions
undefined. /
Free Tier
  • Start free from ECS to Big Data
  • Get Started in 3 Simple Steps
  • Try ECS t5 1C1G
undefined. /

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.