Document directory
- First, the driver
- Use MongoDB in Asp.net
- Add data
- Delete data
- Modify data
- Get Data
First, the driver
If Asp.net wants to use MongoDB,. Net does not have its own link class. Use a third-party or official link class.
Of course there are many drivers, so I will not introduce them one by one.
Today I will introduce a commonly used driver-MongoDB.
Next, we need to download the MongoDB C # driver, which allows us to use MongoDB in C. :
Https://github.com/samus/mongodb-csharp
The driver we need to access MongoDB in C # Is the project MongoDB. Compile this project to get the file name: MongoDB. dll
Use MongoDB in Asp.net
Start MongoDB first. I have already introduced it in my previous articles. I will not introduce it here.
Create an entity-class user table
public partial class User{ [MongoId] public string UID{ get; set; } public string NAME{ get; set; } public string SEX{ get; set; } public int AGE{ get; set; } }
Note: This is a simple class, and the [consumer id] In the code can also be avoided. If it is written, it will map the "_ id" field.
First, create a database named "dbmy", create a set (table) "user", and create a document (data ).
MongoDB. DLL needs to be introduced in the following examples.
Private string _ connectionstring = "Server = 127.0.0.1"; // Database Server IP address or address private string _ dbname = "dbmy ";
Add data
Public void insert (User user) {user. uid = guid. newguid (). tostring ("N"); // first create a connection using (Mongo = new Mongo (_ connectionstring) {// open the connection Mongo. connect (); // switch to the specified database var DB = Mongo. getdatabase (_ dbname); // obtain the corresponding set var collection = dB according to the type. getcollection <user> (); // inserts an object collection into the collection. insert (customer );}}
Delete data
Public void Delete (string UID) {using (Mongo = new Mongo (_ connectionstring) {Mongo. connect (); var DB = Mongo. getdatabase (_ dbname); var collection = dB. getcollection <customer> (); // Delete the specified object collection from the collection. remove (x => X. uid = UID );}}
Modify data
Public void Update (User user) {using (Mongo = new Mongo (_ connectionstring) {Mongo. connect (); var DB = Mongo. getdatabase (_ dbname); var collection = dB. getcollection <user> (); // update object collection. update (user, (x => X. uid = user. UID ));}}
Get Data
Public user getbyid (string UID) {using (Mongo = new Mongo (_ connectionstring) {Mongo. connect (); var DB = Mongo. getdatabase (_ dbname); var collection = dB. getcollection <user> (); // query the return collection of a single object. findone (x => X. uid = UID );}}
Call
Suppose that all the operation methods are encapsulated in a class named test. CS.
Test T = new test (); // insert data t. insert (User); // update data t. update (User); // delete data t. delete (UID );