MongoDB's C # driver basic use

Source: Internet
Author: User
Tags mongoclient mongodb collection mongodb connection string mongodb documentation mongodb driver string format

Reprint: http://www.cnblogs.com/wilber2013/p/4175825.html

MongoDB's Official C # driver can be obtained through this link. The link provides the. msi and. zip two ways to get the drive DLL files.

Through this article to introduce the basic C # Drive database connection, adding and removing changes to check operations.

When using C # drivers, add references to "MongoDB.Bson.dll" and "MongoDB.Driver.dll" in your project. Also add the following two using statements to your code.

Using Mongodb.bson; using Mongodb.driver;
Database connection

To establish a database connection, be sure to know the server's address, port, and so on. All of this information, we use the connection string representation. The connection string format for MongoDB is as follows:

mongodb://[username:[email protected]]host1[:p ort1][, host2[:p Ort2],... [, hostn[:p Ortn]] [/[database][. Options]]     

Here's what each field in the connection string means:

    • MONGODB://: This is the prefix of the MongoDB connection string
    • Username:password (Optional): Optional, indicating login user name and password for user security verification
    • HOSTN: Must specify at least one host that represents the MongoDB instance to which it is connected
    • Portn (Optional): optional, default connection to 27017
    • Database (Optional): If you specify Username:[email protected], connect and verify the login to the specified database. If not specified, the admin database is opened by default.
    • Options (Optional): optional, if you do not use/database, you need to add/. All connection options are key-value pairs Name=value, and key-value pairs are separated by & or; (semicolon)

Here, using the examples in the article "MongoDB Management", Test1 and Test2 have their own users. When accessed using the following connection string, it can be verified correctly because "WILL1:WILL1" has read and write access to test1. If you switch to access the TEST2 database, you get an exception output of "Invalid credentials for database ' Test2 '".

String connectionstr ="Mongodb://will1:[email protected]"; Mongoclient client =New Mongoclient (CONNECTIONSTR); Mongoserver Server = client. Getserver (); Mongodatabase db = server. Getdatabase ("Test2 "student"); try{console. WriteLine ( "db name is: " + db. Name); Console. writeline ( "collections name is: Span class= "hljs-string" + collection. Name); Console. writeline ( "{0} items in this Collection Count ());} catch (Exception e) {console. WriteLine (e.message);}               

As you can see from the code above:

    • How to get client and server objects

      "mongodb://will1:will1@localhost";  Mongoclient client = new Mongoclient (CONNECTIONSTR); mongoserver Server = client. Getserver ();    
    • How to get Databases and collection objects

      Server. Getdatabase ("test2"); Mongocollection<bsondocument> collection = db. GetCollection ("student");     
Bsondocument Object Model

Before you start adding additions and deletions to the introduction, introduce the Bsondocument object model.

In MongoDB collection, each document can be considered as a Bson (Binary JSON) object, so there is a bsondocument type in the driver, you can generate a document in the following way, and add a key/value pair by using the Add method. Bsondocument objects generated in this way can be inserted directly into the collection.

New Bsondocument (); student1. ADD ("SidTen"); Student1. ADD ("name"Will10"); Student1. ADD ("gender"Male "); student1. ADD ("age");               

In MongoDB, there are two ways to do this when the user is working on collection:

    1. Through the Bsondocument object model
    2. by custom type

The Bsondocument object has been described above, and we can also use our own custom types here. For example, we can define a student type that inserts an object of that type into the collection.

student{publicObjectId _id;  int SID; string name; string Gender; int age;}    

Note: Be sure to have an ID field when using a custom type.

Both of the above can be used, and each has the advantage, through the way of custom type, can make the document in the collection a more unified mode, using Bsondocument mode can support more document mode, This means that if a document in a collection has a variety of patterns, the bsondocument approach is more flexible.

Inserting data

For data insertion, we can use the "insert ()" Method in collection. Two records are inserted below. Can be inserted by means of a Bsondocument object, or by a custom type.

By Bsondocument, the user can freely define the format of the document. For example, add a "hobby" field (Ps: This is not recommended, which can cause trouble with document queries).

Bsondocument Student1 =New Bsondocument (); student1. ADD ("Sid",(STUDENT1); ADD ("Name","Will10"); Student1. ADD ("Gender","Male"); Student1. ADD ("Age", student1); ADD ("hobby", new Bsonarray () { "swimming","reading"}), collection. Insert (STUDENT1); Student Student2 = new Student () Student2.age = 27;student2.name = "Wilber"; student2.gender = c19> "Male"; collection. Insert (Student2);                 
Querying data

With MongoDB driver, you can support three different query methods.

Querydocument

The query in this way is similar to our conditional query in the MongoDB shell. For example, a student who is older than 20 is queried

New Querydocument ("AgeNew Querydocument ("$gt"));  foreach (incollection. Find (Querydocument)) {Console.WriteLine (student);}        

When the query condition is multiple, for example, a male student who is older than 20 is queried

Querydocument querydocument = new Querydocument (new Bsonelement ("Age", New Querydocument ("$gt ) , New Bsonelement ("gender","Male"       )); 
Query Builder

Query Builder is a much more concise way, and when queried in this way, we need to use the builder in driver to generate query. So, to reference the following using statement

MongoDB. Driver. Builders; 

The following statement allows you to query for students older than 20

var query = query.gt ("Age-foreach" incollection. Find (query)) {Console.WriteLine (student);}   

Search for male students older than 20

var query = query. and (Query.gt ("age"), Query.eq ("gender"Male"));      

Of course, we can also do strongly typed queries, but this query is conditional, "the requirement that the fields in the document must be a subset of the custom type field, that is, the document can be converted to a specific type." For example, we have inserted a document in front of the "hobby" key, if you use the following method, will produce an exception, indicating that the student type does not hobby this field.

var query = Query<student>. GT (); foreach (incollection. findas<student> (query)) {Console.WriteLine (Student);} 

In this case, you can use the Bsondocument type to query. It is not clear that query using student strong type why not error.

var query = Query<student>. GT (); foreach (incollection. findas<bsondocument> (query)) {Console.WriteLine (student);} 
LINQ Support

After driver's 1.8 release, the official driver can support LINQ operations. We only need to use the following using statement to support the way that LINQ is queried.

MongoDB. Driver. Linq; 

Therefore, you can query the age of more than 20 students, also can be implemented in the following way (note, also ensure that all document can be converted to student type)

In collection. Asqueryable<student> ()                          select E;  var linquery1 = collection. Asqueryable<student> (). Where (a);  

There are many LINQ query operations in the MONGODB documentation, see the LINQ section of the MongoDB document

Update data

There are two ways to update a document by using the Save method to replace the entire document, or by updating the document by using the Update method.

For example, to find this document with SID 9 and name WILL9, update the age field to 27

Save method
var query = query. and (Query.eq ("Sid9), Query.eq ("name"Will9")); Bsondocument Will9 = collection. FindOne (query); null) {will9["age27; Collection. Save (WILL9);}            
Update method
var query = Query.and (Query.eq ("Sid9), Query.eq ("name"Will9"));  var update = update. Set ("age"); collection. Update (query, update);            
Delete data

The operation to delete data is relatively straightforward.

To delete a document for a specific condition:

query = Query.eq ("Sid9); collection. Remove (query);   

Delete all documents:

Collection. RemoveAll ();
Summarize

Through this article learned the basic operation of MongoDB official C # driver.

Of the three ways to query, query Builder is the most flexible, and querying with LINQ is the best way to have a unified schema for all documents, so that you can easily use custom types.

MongoDB's C # driver basic use

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.