1. Installing the MongoDb Driver package
2. Use the wrapper class:
public class Mongodbwrapper:idisposable {private Mongoserver _server; Private Mongodatabase _db; Public Mongodbwrapper () {var uri = configurationsettings.appsettings["Mongourl"]; var url = new Mongourl (URI); var client = new Mongoclient (URL); _server = client. Getserver (); _db = _server. Getdatabase (URL. DatabaseName); } public Mongodbwrapper batchadd<t> (t[] objarray, string collectionname) {var collection = _db. Getcollection<t> (CollectionName); Collection. Insertbatch (Objarray); return this; The public mongodbwrapper add<t> (T obj, string collectionname) {var collection = _db. Getcollection<t> (CollectionName); Collection. Insert (obj); return this; }///<summary>//e.g. {"Age", new Bsondocument {"$gte", "Ten}}}///</summary> <param name= "Query" ></param>///<param name= "CollectionName" ></param> PU Blic void Deleteby<t> (expression<func<t, bool>> whereexp, String collectionname) {var Collection = _db. Getcollection<t> (CollectionName); Collection. Remove (QUERY<T>. Where (WHEREEXP)); } public void update<t> (imongoquery query, String collectionname, T newObj) where t:imongoupdate { var collection = _db. Getcollection<t> (CollectionName); Collection. Update (query, NEWOBJ); } public ienumerable<t> search<t> (expression<func<t, bool>> whereexp, String collectionName ) {var collection = _db. Getcollection<t> (CollectionName); Return collection. Find (QUERY<T>. Where (WHEREEXP)). ToList (); } public T single<t> (expression<func<t, bool>> whereexp, string collectIonname) {return Search (Whereexp, CollectionName). Single (); The public void Removecollection (string collectionname) {_db. Dropcollection (CollectionName); public void Dispose () {_server. Disconnect (); } }
3 Examples of usage of some related operations
Query var driver = dbwrapper.single<driver> (d = d.name = = Name, dbcollectionname.for<driver> ()); var drivers = Dbwrapper.search<driver> (d = = D.name = = Name, dbcollectionname.for<driver> ()); Delete Dbwrapper.deleteby <Job> (j = j.id = = Id, dbcollectionname.for<publicqueue> ()); remove var updatingnw = update<network> from the collection . Pull (NW = NW. Jobs, ajobfromqueue); Dbwrapper.update (QUERY<NETWORK>. Where (n = n.name = = Name), dbcollectionname.for<network> (), UPDATINGNW); Add new item to collection var UPDATINGDP = update< Dispatcher>. Addtoset<dynamic> (d = d.pendingjobs, ajobfromqueue); Dbwrapper.update (QUERY<DISPATCHER>. Where (d = d.name = = Name), dbcollectionname.for<dispatcher> (), UPDATINGDP); Update Dbwrapper.update (query< Network>. Where (n = n.name = = Name), dbcollectionname.for<network> (), UPDATINGNW);
The above is the content of MongoDB C # Wrapper class (MongoDB Driver 1.9), and more about topic.alibabacloud.com (www.php.cn)!