use official Drive operations in C # MongoDB
8.1) Download and install
To use MongoDB in C #, you first have to have a MongoDB supported C # version of the drive. The C # version of the drive has many kinds, such as the official offer, Samus. The implementation of ideas are mostly similar. Here we first use the official Mongo-csharp-driver, the current version is 1.4.1
Download Address: Http://github.com/mongodb/mongo-csharp-driver/downloads
Two DLLs after compilation
MongoDB.Driver.dll: As the name suggests, the driver
MongoDB.Bson.dll: serialization, JSON-related
Then refer to these two DLLs in our program.
The following section briefly demonstrates how to use C # to make a MongoDB check operation.
8.2) Connecting to the database:
Make sure your MongoDB is turned on before connecting to the database.
Database connection string
const string strconn = "mongodb://127.0.0.1:27017";
Database name
const string dbname = "Cnblogs";
Create a database link
mongoserver server = MongoDB.Driver.MongoServer.Create (strconn);
Get database cnblogs
mongodatabase db = server. Getdatabase (dbname);
8.3) Insert data:
Okay, now that the data is open, we need to add the data, and we're going to add a user "record" to the Users collection.
There is no concept of a table in MongoDB, so you do not need to create a table before inserting data.
But we have to define a model for the data to insert. Users
Users.cs: Public
class
the Users {public
ObjectId _id;//bsontype.objectid This corresponds to MongoDB.Bson.ObjectId
public string Name {get; set;}
public string Sex {set; get;}
}
The _id attribute must be available, otherwise the data will be updated with an error: "Element ' _id ' does not match any field or ' class".
OK, now look at how the code that adds the data is written:
public void Insert ()
{
//CREATE DATABASE link
mongoserver server = MongoDB.Driver.MongoServer.Create (strconn);
Get database cnblogs
mongodatabase db = server. Getdatabase (dbname);
Users users = new users ();
Users. Name = "Xumingxiang";
Users. Sex = "man";
Get the Users collection and, if not in the database, create a new
mongocollection col = db first. GetCollection ("Users");
Performs an insert Operation
Col. Insert<users> (Users);
}
8.4) Update Data
public void Update ()
{
//CREATE DATABASE link
mongoserver server = MongoDB.Driver.MongoServer.Create (strconn);
Get database cnblogs
mongodatabase db = server. Getdatabase (dbname);
Gets the Users collection
mongocollection col = db. GetCollection ("Users");
Define query criteria to get "name" value "Xumingxiang"
= new Querydocument {{"name", "Xumingxiang"}};
Define update document
var update = new UpdateDocument {{' $set ', new Querydocument {{' Sex ', ' Wowen '}}}};
Perform the update operation
Col. Update (query, update);
}
8.5) Delete Data
public void Delete ()
{
//CREATE DATABASE link
mongoserver server = MongoDB.Driver.MongoServer.Create (strconn);
Get database cnblogs
mongodatabase db = server. Getdatabase (dbname);
Gets the Users collection
mongocollection col = db. GetCollection ("Users");
Define query criteria to get "name" value "Xumingxiang"
= new Querydocument {{"name", "Xumingxiang"}};
Perform the delete operation
Col. Remove (query);
8.6) Query data
public void Query ()
{
//CREATE DATABASE link
mongoserver server = MongoDB.Driver.MongoServer.Create (strconn);
Get database cnblogs
mongodatabase db = server. Getdatabase (dbname);
Gets the Users collection
mongocollection col = db. GetCollection ("Users");
Define query criteria to get "name" value "Xumingxiang"
= new Querydocument {{"name", "Xumingxiang"}};
Query the data in all collections
var result1 = col. Findallas<users> ();
query specifies the first piece of data for a query condition, which can be default.
var result2 = col. Findoneas<users> ();
query specifies all data for query criteria
var result3 = col. findas<users> (query);
MongoDB is used in C #
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Runtime.Serialization;
Using System.Data;
Using System.Data.SqlClient;
Using Mongodb.bson;
Using Mongodb.driver; Namespace ConsoleApplication1 {class Program {static void Main (string[] args) {//connection
Information String conn = "Mongodb://localhost";
string database = "Demobase";
String collection = "Democollection"; Mongoserver MongoDB = mongoserver.create (conn);//Connection database Mongodatabase Mongodatabase = MongoDB. Getdatabase (DB)//Select database name mongocollection mongocollection = Mongodatabase.getcollection (collection);//Select Set The equivalent of a table MongoDB.
Connect ();
Normal insert var o = new {Uid = 123, Name = "Xixinormal", PassWord = "111111"};
Mongocollection.insert (o); Object Inserts person p = new Person {Uid = 124, Name = "Xixiobject", PassWord = "222222 "};
Mongocollection.insert (P);
bsondocument Insert Bsondocument B = new Bsondocument ();
B.add ("Uid", 125);
B.add ("Name", "Xixibson");
B.add ("PassWord", "333333");
Mongocollection.insert (b);
Console.ReadLine ();
The class Person {public int Uid;
public string Name;
public string PassWord; }
}
Results:
Are written in the above configuration, the program automatically creates the corresponding libraries and collections.
The following operation does not have the complete code:
/*---------------------------------------------* sql:select * FROM table *------ ---------------------------------------*/mongocursor<person> p = Mongocollection.findalla
S<person> ();
/*---------------------------------------------* sql:select * from table WHERE UID > UID < 20 *---------------------------------------------*/querydocument query = new Querydo
Cument ();
Bsondocument B = new Bsondocument ();
B.add ("$gt", 10);
B.add ("$lt", 20); Query.
ADD ("Uid", b);
mongocursor<person> m = mongocollection.findas<person> (query); /*-----------------------------------------------* sql:select COUNT (*) from table WHERE Uid > and Ui D < *-----------------------------------------------/Longc = mongocollection.count (query); /*-----------------------------------------------* sql:select Name from table WHERE UID > UID ; *-----------------------------------------------* * querydocument query = new query
Document ();
Bsondocument B = new Bsondocument ();
B.add ("$gt", 10);
B.add ("$lt", 20); Query.
ADD ("Uid", b);
Fieldsdocument f = new fieldsdocument ();
F.add ("Name", 1); mongocursor<person> m = mongocollection.findas<person> (query).
Setfields (f);
/*-----------------------------------------------* sql:select * FROM table order by Uid DESC LIMIT 10,10 *-----------------------------------------------*/querydocument query = new Querydocum
ENT ();
sortbydocument s = new sortbydocument (); S.add ("Uid",-1);//-1=desc Mongocursor<person> m = mongocollection.findallas<person> (). SetSortOrder (s). Setskip (10). Setlimit (10);
using Samus driver operations in C # MongoDB
To introduce a third party drive Samus, this is a use of a more driven, updated faster, Samus driver in addition to supporting the general form of operations, but also support LINQ and lambda expressions.
Download Address: Https://github.com/samus/mongodb-csharp
Download back compile to get two DLLs
Main program driven by MongoDB.dll
MongoDB.GridFS.dll is used to store large files.
Here we can quote MongoDB.dll. About MongoDB.GridFS.dll This article does not use, temporarily does not introduce, ignores it.
Its connection database and CRUD operations are as follows:
Database connection String Const string strconn = "mongodb://127.0.0.1:27017";
Database name const string dbname = "Cnblogs";
Define database Mongodatabase db; <summary>///Open Database link///</summary> public void getconnection () {//define Mongo service Mongo Mongo = new Mong
O (strconn); Open the connection MONGO.
Connect (); Get the database cnblogs, and automatically create DB = MONGO If it does not exist.
Getdatabase (dbname) as mongodatabase; ///<summary>///Add data///</summary> public void Insert () {var col = db.
Getcollection<users> (); or//var col = db.
GetCollection ("Users");
Users users = new users (); Users.
Name = "Xumingxiang"; Users.
Sex = "Man"; Col.
Insert (users); ///<summary>///Update data///</summary> public void Update () {var col = db.
Getcollection<users> (); Finds the first record of the name value of Xumingxiang the users users = Col.
FindOne (x => x.name = = "Xumingxiang"); or//users Users = Col.
FindOne (new Document {{"Name", "Xumingxiang"}}); Users.
Sex = "Women"; Col. Update (Users, x => x.sex = = "Man"); ///<summary>///Delete data///</summary> public void Delete () {var col = db.
Getcollection<users> (); Col.
Remove (x => x.sex = = "Man"); Or////find the first record of the name value Xumingxiang//users Users = col.
FindOne (x => x.sex = "man"); Col.
Remove (users); ///<summary>///Query data///</summary> public void query () {var col = db.
Getcollection<users> ();
var query = new Document {{' Name ', ' Xumingxiang '}}; query specifies all data for query criteria var result1 = Col.
Find (query); query specifies the first data of the query criteria var result2 = Col.
FindOne (query); Query the data in all collections var result3 = Col.
FindAll (); }
Querydocument's Common query:[CSharp] View Plain Copy/*--------------------------------------------- * sql : select * from table where configid > 5 and objid = 1 *--------------------------------------------- */ querydocument query = new querydocument (); bsondocument b = new Bsondocument (); b.Add ("$gt" , 5); query. ADD ("Configid", b); query. ADD ("ObjID", 1); Mongocursor<person> m = mongocollection.findas<person > (query); /*--------------------------------------------- * sql : select * from table where configid > 5 and configid < 10 *--------------------------------------------- */ querydocument query = new Querydocument (); Bsondocument b = new bsondocument (); B.add ("$gt", 5); B.add ("$lt", 10); query. ADD ("Configid", b); mongocursor<person> m = mongocollection.findas< Person> (query);
1 public class News
2 {
3 public int _id {get; Set; }
&n