To use MongoDB in C #, you first have to have a mongodb-supported C # version of the driver. The C # version of the driver seems to have many kinds, such as the official Samus. The idea of implementation is mostly similar. Here we use the officially provided Mongo-csharp-driver:
: Http://github.com/mongodb/mongo-csharp-driver/downloads
Get two DLLs after decompression:
MongoDB.Driver.dll: As the name implies, the driver
MongoDB.Bson.dll: serialization, JSON-related
We then refer to these two DLLs in our program.
2. Connect to the database
[CSharp]View PlainCopy
- Using Mongodb.bson;
- Using Mongodb.driver;
[CSharp]View PlainCopy
- Database connection string
- Const String strconn = "mongodb://127.0.0.1:27017";
- Database name
- Const String dbName = "Test";
- Mongoserver server;
- Mongodatabase DB;
- void Init ()
- {
- //Create a database link
- Server = MongoDB.Driver.MongoServer.Create (strconn);
- //Access to the database
- db = Server. Getdatabase (DbName);
- }
3. Query data
1) Query rule collection
[CSharp]View PlainCopy
- Class Users
- {
- Public ObjectId _id; //bsontype.objectid this corresponds to MongoDB.Bson.ObjectId.
- public string Name { get; set;}
- public string Sex { set; get;}
- }
- Const String ENTER = "\ r \ n";
- Private void Btnquery_click (object sender, EventArgs e)
- {
- //Get the Users collection
- Mongocollection col = db. GetCollection ("Users");
- //Query the data in all collections
- var result1 = Col. Findallas<users> (). ToList ();
- StringBuilder sb = new StringBuilder ("");
- foreach (Users user in (list<users>) result1)
- {
- Sb. Append (user. Name + ENTER);
- }
- MessageBox.Show (sb.) ToString ());
- }
This approach is only suitable for collections where each document structure is identical:
But one of the arguments for NoSQL's criticism of relational databases is that this so-called structure of each record should be consistent, because some fields are not required for all records. So, in MongoDB here, for the collection of Chinese document structure is inconsistent, the above code gets no data, it seems that the following methods should be used:
2) Query Irregular collection
Set Condition:
In the collection thins, basically each document structure is different.
Find the following code:
[CSharp]View PlainCopy
- Private void Btnquery2_click (object sender, EventArgs e)
- {
- //Get Thins collection
- Mongocollection col = db. GetCollection ("Thins");
- //Query the data in all collections
- var result1 = Col. Findallas<bsondocument> (). ToList ();
- StringBuilder sb = new StringBuilder ("");
- foreach (bsondocument bd in (list<bsondocument>) result1)
- {
- String name = Bd. Contains ("name")? Bd. GetValue ("name"). ToString (): "does not exist";
- Sb. Append (name + ENTER);
- }
- MessageBox.Show (sb.) ToString ());
- }
Usage of MongoDB Query