Getting Started with MongoDB for C # basics

Source: Internet
Author: User
Tags mongoclient

The author uses the. NET driver recommended by MongoDB website:

http://mongodb.github.io/mongo-csharp-driver/2.0/getting_started/quick_tour/

For MongoDB installation readers can refer to other blogs, for basic learning does not require excessive configuration.

Create a connection

This step is the same as the steps of ADO to connect to the database, ADO uses SqlConnection to connect to the database, and MongoDB use Mongoclient connection, and in the constructor to pass the connection character in, of course, can not be passed, then the default This is the default port (27017) of the local computer, such as the following three connection types:

New mongoclient ();  New Mongoclient ("mongodb://localhost:27017");  New Mongoclient ("mongodb://localhost:27017,localhost:27018,localhost:27019");    

Get database

In order to get the database, just call the getdatabase method of the mongoclient object and pass in the database name, and if the database exists, return directly, otherwise create the database and return it, for example, the following code will create a name named Database for "foo":

var database = client. Getdatabase ("foo");  

Now the database variable is pointing to the Foo data base.

Get linked List

Although it is called to get the list, but in fact is to get the table in the database, we can get through the getcollection<tdocument> method above, such as the following code we will get a table named "Bar":

var collection = database. Getcollection<bsondocument> ("bar");  

The generic parameter we passed in is bsondocument, which is self-contained, can dynamically accommodate data in various formats, and of course it is recommended that the reader use Poco.

Insert a document

With the collection object, we can insert the document into it, such as the following JSON-formatted data:

{     "name": "MongoDB",     "type": "Database",     "Count": 1,     "info": {         x:203, y : 102 }}     

Below we use the bsondocument object to organize the above JSON-formatted data:

var document =Newbsondocument{{"Name","Mongodb"}, {"Type", "database" }, { "count1info ", new bsondocument{{ "x203}, { "y102           

We then use the insertoneasync of the collection object to insert the above data:

Collection. Insertoneasync (DOC);

We all know that async is the suffix of the method is asynchronous, but the author is shown in the console project so did not add this await, if the reader is really other environment testing can be added according to the situation.

Inserting multiple documents

If you need to insert multiple documents at once, we can pass the Insertmanyasync method, such as the following example we will insert 100 data:

var documents = Enumerable.range (new Bsondocument ("counter", x)); collection. Insertmanyasync (documents);    

Number of statistical documents

Through the above steps we have inserted 101 data, if in actual development we need to count the number of data can be called by the Countasync method, such as the following code:

var count = collection. Countasync (new bsondocument ()); Console.WriteLine (count. Result); 

Query linked list

Using the Find method we can query the linked list, the Find method will return to our ifindfluent<tdocument,tprojection> object, which is a chain interface, So we can provide a chain like jquery to change the way to control the query operation.

Querying the first data of a linked list

To get the first piece of data we can call the Firstordefaultasync method, which returns the first data, or null if there is no data, such as the following code will show the first data in the list:

var Firstdoc = collection. Find (new bsondocument ()). Firstordefaultasync (); Console.WriteLine (FirstDoc.Result.ToString ()); 

If the reader is aware of the final output, it will find a _id field, but we do not insert this field, this field is MongoDB automatically added, I believe many people know its role, there is no detailed explanation of the amount.

Querying all data in a linked list

If you want to return all the data in the list and call the Tolistasync method after the find operation, you will return the result of the list<t> type directly, such as this code:

var documents = collection. Find (new Bsondocument ()). Tolistasync (). Result;

There is no problem with a small amount of data, but if we need to deal with a large amount of data, then we cannot use the above method, we need to use the following way, through the foreachasync to complete, Because this method executes a callback when each data is returned, for the purpose of concurrent processing, such as the following code demonstrates how to use:

Collection. Find (new Bsondocument ()). Foreachasync (x = Console.WriteLine (x));

Querying single data by condition

We can call the Find method to pass a filter condition, in order to query the list of the data we want, such as the following example we will query the field "Counter" value of 71 data:

var filter = Builders<bsondocument>. Filter.eq ("counter");  var document = collection. Find (filter). Firstasync (). Result; Console.WriteLine (document);     

Here we need to construct the condition through the various conditional methods in the Builders static object Filter , and then pass it in when the Find method is called.

Querying multiple data by condition

We can also get a number of data, such as the following example, we will search for all "counter" value greater than 50 of the data:

var filter = Builders<bsondocument>. FILTER.GT ("counter");  var document = collection. Find (filter). Foreachasync (x = Console.WriteLine (x));    

Of course we can also give a range, such as between 50 and 70:

var filterbuilder = builders<bsondocument>. Filter; var filter = filterbuilder.gt ("counter") & filterbuilder.lt ("counter"); Collection. Find (filter). Foreachasync (x = Console.WriteLine (x));        

Sort the data

Below we will add a sort on the basis of the query, sorting only needs to pass in the corresponding parameter when the sort method is called, such as the following example, we will query the linked list first, and then sort:

var filter = Builders<bsondocument>. Filter.exists ("counter");  var sort = builders<bsondocument>. Sort.descending ("counter");  var documnt = collection. Find (filter). Sort (sort). Firstasync (). Result;         

Casting on fields

Many times we don't need all the data in the document, it's like in SQL we just select the data we need instead of all the fields in the table, and naturally mongodb can let me do it, we just have to use it like filtering and sorting. The Projection constructor is constructed and then passed to the Project method, and in the following example we will exclude the "_id" field:

var projection = Builders<bsondocument>. Projection.exclude ("_id");  var document = collection. Find (new bsondocument ()). Project (projection). Firstasync (). Result; Console.WriteLine (document);      

Update document

MongoDB has a lot of update operations, and below we'll cover a few simple and common update operations.

If we need to update an object (which might be 0 if the condition does not match), you can use the Updateoneasync method and execute the filter and the document that needs to be updated, such as below we will "counter" the "counter" in the data for 1 is updated to 110:

var filter = Builders<bsondocument>. Filter.eq ("counter1");  var updated = Builders<bsondocument>. Update.set ("counter");  var result = collection. Updateoneasync (filter, updated). Result;         

If we need a batch update, we can call Updatemanyasync . For example, we need to add 100 to the " counter" in the data "counter" less than 10, so we can write like this:

var filter = Builders<bsondocument>. filter.lt ("counter");  var updated = Builders<bsondocument>. Update.inc ("counter");  var result = collection. Updatemanyasync (filter, updated). Result;         

Delete a document

As the base part this is also the last part, using the above filter, and then call the deleteoneasync or deletemanyasync method is OK, such as the following example is deleted " Counter " more than 100 of all data:

var filter = Builders<bsondocument>. FILTER.GT ("counter");  var Resut = collection. Deletemanyasync (filter). Result;    

Getting Started with MongoDB for C # basics

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.