MongoDB's official drive: https://github.com/mongodb/mongo-csharp-driver/releases
Currently the latest version is 2.10, which supports. NET 4.5 or more. Because my current program is still here. NET4.0 built above, so use the 1.10.1 version here.
Add Reference
Unzip the downloaded driver and add a reference to our program:
MongoDB.Bson.dll
MongoDB.Driver.dll
Then add the using in your code:
Mongodb.bson; mongodb.driver;
Create client, Server, Database
"mongodb://localhost:27017" ; mongoclient (connectionString); Server = client. Getserver (); db = server. Getdatabase ("MyDB");
ConnectionString can be obtained from the configuration file.
The client object is thread-safe, so we can save it in a global variable.
With the DB object, we can access it.
Using collection
Collection is a collection of documents that can be understood as our data tables. And each document is a row of our data. In the MongoDB driver, we have two ways to use the collection:
- Using the Bsondocument model
- Using a custom entity model
It is recommended to use the Bsondocument model if our document structure is more complex or is difficult to define as a solid model.
If our document structure is clear and the stored fields are fixed, we recommend using a custom entity model. The format of the entity object is as follows:
Entity { get set;} get set;} }
When we get the collection reference, we need to provide a document type:
collection = db. getcollection<Entity> ("entities");
Curd operation
After having the collection, we can write an example of curd:
varcollection = db. getcollection<Entity> ("Entities");varentity =NewEntity{Name ="Tom"};collection. Insert (entity);varID = entity. Id;varquery =Query<Entity. EQ (E = e.id, Id); entity = collection. FindOne (query); entity. Name ="Dick"; collection. Save (entity);varupdate =Update<Entity. Set (E = e.name,"Harry."); collection. Update (query, update); collection. Remove (query);
Fei Qi ([email protected])
Original link: http://www.qeefee.com/article/000559
Using the official drive to manipulate MongoDB in C #