1. Download official for C # driver 2, import 2 DLL file 3, connection string
<add key="mongoconn" value="mongodb://127.0.0.1:27017"/ > <add key="Database" value="mytest"/ >
4. Get Mongodatabase Object
Public Static mongodatabase getmongodatabase () { new mongoclient (configurationmanager.appsettings["mongoconn" ) ]); = mongoclient.getserver (); return mongoserver.getdatabase (configurationmanager.appsettings["Database "]); }
5. New Model Object
You can specify the actual field name in the table
[Bsonelement ("_id")] PublicObjectId Id {Get;Set; } [Bsonelement ("name")] Public stringName {Get;Set; } [Bsonelement ("Sex")] Public stringSex {Get;Set; } [Bsonelement ("sec")] Public stringSec {Get;Set; } [Bsonelement ("SD")] Public stringSd {Get;Set; } [Bsonelement (" Age")] Public intAge {Get;Set; }
6. Enquiry
// imongoquery query= Query.eq ("name", "Hao"); Query condition mongocursor<usermodel> res = Mongohelper.getmongodatabase (). GetCollection ("users"). Findallas<usermodel>(); = res; return View ();
7. Insert the encapsulated model object
Publicactionresult Insert (Usermodel usermodel) {writeconcernresult res= Mongohelper.getmongodatabase (). GetCollection ("Users"). Insert (Usermodel); if(Res. Ok) {returnJson ("Add Success", Jsonrequestbehavior.allowget); } returnJson ("Add failed", Jsonrequestbehavior.allowget); }
8, according to Objectid delete
Imongoquery query = Query.eq ("_id",NewBsonobjectid (id)); Writeconcernresult Res= Mongohelper.getmongodatabase (). GetCollection ("Users"). Remove (query); if(Res. Ok) {returnJson ("Delete succeeded", Jsonrequestbehavior.allowget); } returnJson ("Delete Failed", Jsonrequestbehavior.allowget);
9. Update data
You can use the Save method or the Update method to make the Save method more convenient.
PublicActionResult Edit (stringID) {Usermodel res=mongohelper.getmongodatabase (). GetCollection ("Users"). Findonebyidas<usermodel> (NewBsonobjectid (id)); Viewdata.model=Res; returnView (); } [HttpPost] PublicActionResult Edit (Usermodel Usermodel,stringId) {//the ID of Usermodel here cannot be obtained to be converted to ObjectidUsermodel.id=NewObjectId (Id); //The save operation will update with the same ID as the ID update with no matching additionsWriteconcernresult res = Mongohelper.getmongodatabase (). GetCollection ("Users"). Save (Usermodel); //You can also use the following method//Writeconcernresult res = Mongohelper.getmongodatabase (). GetCollection ("Users"). Update (Query.eq ("_id", New Bsonobjectid (Usermodel.id)), New UpdateDocument (Usermodel.tobsondocument () )); if(Res. Ok) {returnJson ("Update Successful", Jsonrequestbehavior.allowget); } returnJson ("Update failed", Jsonrequestbehavior.allowget); }
MongoDB basic operation of the. Net