Using the official drive to manipulate MongoDB in C #

Source: Internet
Author: User
Tags findone

Using the official drive to manipulate MongoDB in C #

8.1) Download and install

To use MongoDB in C #, you first have to have a mongodb-supported C # version of the driver. There are many kinds of drivers for the C # version, such as the official Samus. The idea of implementation is mostly similar. Here we first use the officially provided mongo-csharp-driver, the current version is 1.4.1

: Http://github.com/mongodb/mongo-csharp-driver/downloads

Get two DLLs after compiling

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.

The following section shows you how to use C # to add and revise MongoDB.

8.2) Connect to the database:

Before connecting to the database, make sure that your MongoDB is turned on.

Database connection String Const string strconn = "mongodb://127.0.0.1:27017"; Database name const string dbName = "cnblogs";//CREATE DATABASE link Mongoserver server = MongoDB.Driver.MongoServer.Create (strconn); Obtain the database cnblogs mongodatabase db = server. Getdatabase (DbName);

8.3) Insert data:

Okay, now that the data is open, you have to add the data, and we're going to add a user "record" to the Users collection.

There is no concept of tables in MongoDB, so it is not necessary to create a table before inserting the data.

But we have to define the model for the data to be inserted. Users

Users.cs: Public    class Users    {public        ObjectId _id;//bsontype.objectid This corresponds to MongoDB.Bson.ObjectId  public string Name {get; set;}        public string Sex {set; get;}    }

The _id property must be there, or the data will be updated with an error: "Element ' _id ' does not match any field or property of Class".

OK, now look at how the code for adding data is written:

public void Insert () {    //CREATE DATABASE link Mongoserver server = MongoDB.Driver.MongoServer.Create (strconn);    Obtain the database cnblogs mongodatabase db = server. Getdatabase (dbName);    Users users = new users ();    Users. Name = "Xumingxiang";    Users. Sex = "man";    Get the Users collection, if not in the database, create a new mongocollection col = db first. GetCollection ("Users");    Executes the insert Operation Col. Insert<users> (Users);}

8.4) Update Data

public void Update () {    //CREATE DATABASE link Mongoserver server = MongoDB.Driver.MongoServer.Create (strconn);    Obtain the database cnblogs mongodatabase db = server. Getdatabase (dbName);    Gets the Users collection mongocollection col = db. GetCollection ("Users");    Defines a query condition that gets the "name" value of "Xumingxiang" var query = new Querydocument {{"name", "Xumingxiang"}};    Definition 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);    Obtain the database cnblogs mongodatabase db = server. Getdatabase (dbName);    Gets the Users collection mongocollection col = db. GetCollection ("Users");    Defines a query condition that gets the "name" value of "Xumingxiang" var query = 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);    Obtain the database cnblogs mongodatabase db = server. Getdatabase (dbName);    Gets the Users collection mongocollection col = db. GetCollection ("Users");    Defines a query condition that gets the "name" value of "Xumingxiang" var query = new Querydocument {{"name", "Xumingxiang"}};              Query the data in all collections var result1 = Col. Findallas<users> ();    Queries the first data for the specified query criteria, which can be defaulted. var result2 = Col. Findoneas<users> ();    Query all data for the specified 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);//Connect database Mongodatabase mongodatabase = MongoDB. Getdatabase (database);//Select the DB name mongocollection mongocollection = Mongodatabase.getcollection (collection);//Select Collection , which is equivalent to table MongoDB.            Connect ();            Normal insert var o = new {Uid = 123, Name = "Xixinormal", PassWord = "111111"};            Mongocollection.insert (o);            Object Insert 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 ();        }} class Person {public int Uid;        public string Name;    public string PassWord; }}

Results:

Are written in the above configuration, the program will automatically establish the corresponding libraries and collections.

The following operation is not complete code:

            /*---------------------------------------------* sql:select * FROM table *-------- -------------------------------------*/mongocursor<person> p = mongocollection.findallas&lt ;            Person> ();             /*---------------------------------------------* sql:select * from table WHERE Uid > UID < 20 *---------------------------------------------*/querydocument query = new Querydocume            NT ();            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 > Ten and UID < *-----------------------------------------------* */long C = mongocollection.c OUNT (query);  /*-----------------------------------------------* sql:select Name from table WHERE UID > UID < *-----------------------------------------------* * querydocument query = new Querydo            Cument ();            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 Querydocument (            );            sortbydocument s = new sortbydocument (); S.add ("Uid",-1);//-1=desc mongocursor<person> m = mongocollection.Findallas<person> (). SetSortOrder (s). Setskip (10). Setlimit (10);

Using the Samus driver to manipulate MongoDB in C #

Introduce a third-party driver Samus, which is a use of more drivers, update frequency is faster, Samus driver in addition to support the general form of operation, but also support LINQ and lambda expressions.

: Https://github.com/samus/mongodb-csharp

Download back compile to get two DLLs

MongoDB.dll Driver's main program

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 MONGO (strconn); Open the connection MONGO.    Connect (); Obtain 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> (); The first record that has the name value Xumingxiang is detected by 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 with 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 all data for the specified query criteria var result1 = Col.    Find (query); Queries the first data for the specified query criteria var result2 = Col.    FindOne (query); Query the data in all collections var result3 = Col. FindAll ();}

Common queries for querydocument:

[CSharp]View Plaincopy
  1. /*---------------------------------------------
  2. * Sql:select * FROM table WHERE configid > 5 and ObjID = 1
  3. *---------------------------------------------
  4. */
  5. querydocument query = new Querydocument ();
  6. Bsondocument B = new Bsondocument ();
  7. B.add ("$gt", 5);
  8. Query.  ADD ("Configid", b);
  9. Query.  ADD ("ObjID", 1);
  10. mongocursor<person> m = mongocollection.findas<person> (query);
  11. /*---------------------------------------------
  12. * Sql:select * FROM table WHERE configid > 5 and Configid < 10
  13. *---------------------------------------------
  14. */
  15. querydocument query = new Querydocument ();
  16. Bsondocument B = new Bsondocument ();
  17. B.add ("$gt", 5);
  18. B.add ("$lt", 10);
  19. Query.  ADD ("Configid", b);
  20. mongocursor<person> m = mongocollection.findas<person> (query);

1 public class News
2 {
3 public int _id {get; set;}
4 public int count {get; set;}
5 public string News {get; set;}
6 Public DateTime Time {get; set;}
7}
8
9 mongocursor<bsondocument> alldoc = coll. Findallas<bsondocument> ();
Ten bsondocument doc = Alldoc.first (); Bsondocument type parameter
11
mongocursor<news> allnews = Coll. Findallas<news> ();
News anew = Allnews.first (); News type parameters
14
News firstnews = Coll. Findoneas<news> (); Find the first document
16
querydocument query = new querydocument (); Defining a query Document
Query. ADD ("_id", 10001);
Query. ADD ("Count", 1);
mongocursor<news> qnews = Coll. findas<news> (query);
21st
22
bsondocument bd = new bsondocument ();//define Query document COUNT&GT;2 and count<=4
Bd. ADD ("$gt", 2);
Bd. ADD ("$lte", 4);
Querydocument query_a = new Querydocument ();
Query_a.add ("Count", BD);
28
Fieldsdocument fd = new Fieldsdocument ();
FD. ADD ("_id", 0);
FD. ADD ("Count", 1);
FD. ADD ("Time", 1);
33
mongocursor<news> MNEWSS = Coll. Findas<news> (query_a). Setfields (FD);//returns only count and time
35
$ var time = bsondatetime.create ("2011/9/5 23:26:00");
Panax Notoginseng bsondocument db_t = new Bsondocument ();
Db_t.add ("$gt", time);
Querydocument qd_3 = new Querydocument ();
Qd_3.add ("Time", db_t);
41
mongocursor<news> mnews = Coll. Findas<news> (qd_3);//

http://blog.csdn.net/lansetiankong12/article/details/51767630

Using the official drive to manipulate MongoDB in C #

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.