Summary: This article only provides a QuickStart level for using C # driver Operations MongoDB, a master skips
- Downloading the C # Driver
- Bash download
- To add a related DLL reference
MongoDB.Bson.dll MongoDB.Driver.dll
- Add a namespace reference
using Mongodb.bson; using Mongodb.driver;
- Get Client Object
var " Mongodb://localhost " ; var New Mongoclient (connectionString);
- Get server-side objects
var server = client. Getserver ();
- Get the database to manipulate
var database = server. Getdatabase ("test"// "Test " is the name of the database
- CRUD (use a custom Class)
- Custom Entities
Public class entity{ publicgetset;} Public string Get Set ; }}
- Get the table to manipulate
// "Entities" is the name of the collection var collection = database. Getcollection<entity> ("entities");
- Add a record
var New " Tom " };collection. Insert (entity); var // Insert would set the Id if necessary (as it is in this example)
- Query a record
var query = Query<entity>. EQ (E = e.id, Id); var entity = collection. FindOne (query);
- Save a record (send entire entity to database)
" Dick " ; collection. Save (entity);
- Modify a record ( send only the modified part to the database, which is the same as the save or the difference, depending on the scene from the row to determine which one to use to update the data )
var query = Query<entity>. EQ (E = e.id, Id); var " Harry " // Update Modifierscollection. Update (query, update);
- Delete a record
var query = Query<entity>. EQ (E = e.id, Id); collection. Remove (query);
Full Demo Code:
1 usingMongodb.bson;2 usingMongodb.driver;3 usingMongoDB.Driver.Builders;4 usingSystem;5 usingSystem.Collections.Generic;6 usingSystem.Linq;7 usingSystem.Linq.Expressions;8 usingSystem.Text;9 usingSystem.Threading.Tasks;Ten One namespacemongodbtest A { - class Program - { the Static voidMain (string[] args) - { - varConnectionString ="mongodb://localhost:27017"; - varClient =Newmongoclient (connectionString); + varServer =client. Getserver (); - varDatabase = Server. Getdatabase ("Test"); + varCollection = database. Getcollection<entity> ("entities"); A varentity =NewEntity {Name ="Tom" }; at vari =collection. Insert (entity); - varID =entity. Id; - - varquery = Query<entity>. EQ (E =e.id, Id); -entity =collection. FindOne (query); -Entity. Name ="Dick"; in vars =collection. Save (entity); - to varUpdate = Update<entity>. Set (e = e.name,"Harry"); + collection. Update (query, update); - the * collection. Remove (query); $ Panax Notoginseng Console.readkey (); - the } + A the } + Public classEntity - { $ PublicObjectId Id; $ Public stringName {Get;Set; } - } - the}
Mongodb-getting Started with the C # Driver