MongoDB's C # driver basic use

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

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 '".

stringConnectionStr ="Mongodb://will1:[email protected]"; Mongoclient Client=Newmongoclient (CONNECTIONSTR); Mongoserver Server=client. Getserver (); Mongodatabase DB= Server. Getdatabase ("test2"); Mongocollection<BsonDocument> collection = db. GetCollection ("Student");Try{Console.WriteLine ("DB name is:"+db.    Name); Console.WriteLine ("Collections name is:"+collection.    Name); Console.WriteLine ("{0} items in this collection", collection. Count ());}Catch(Exception e) {Console.WriteLine (e.message);}

As you can see from the code above:

    • How to get client and server objects
      string " Mongodb://will1:[email protected] "  new= client. Getserver ();
    • How to get Databases and collection objects
      Mongodatabase db = 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.

Bsondocument Student1 =Newbsondocument (); student1. ADD ("Sid",Ten); 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.

 Public class student{    public  ObjectId _id;      Public int Sid;      Public string name;      Public string gender;      Public 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 =Newbsondocument (); student1. ADD ("Sid",Ten); Student1. ADD ("name","Will10"); Student1. ADD ("Gender","Male"); Student1. ADD (" Age", -); Student1. ADD ("Hobby",NewBsonarray () {"Swimming","Reading"}); collection. Insert (STUDENT1); Student Student2=NewStudent (); Student2.age= -; Student2.name="Wilber"; Student2.gender="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 ("Age"new querydocument ("$gt",  )); foreach (var in collection.) Find (querydocument)) {    Console.WriteLine (student);}

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

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

using MongoDB.Driver.Builders;

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

var query = query.gt ("Age" (var inch collection. 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, "therequirement 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  - ); foreach (var in collection.) 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  - ); foreach (var in collection.) 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.

using 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)

var  from  in collection. Asqueryable<student>()             where             Select  e; var );

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 ("sid"9), Query.eq ("name  "Will9"= collection. FindOne (query); if NULL {    will9["Age");    Collection. Save (WILL9);}
Update method
var query = Query.and (Query.eq ("sid"9), 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:

var query = Query.eq ("sid"9); 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.