Detailed MongoDB for C # basics Getting Started _c# tutorials

Source: Internet
Author: User
Tags mongoclient mongodb

The author here is the MONGODB official website recommended to use. NET drive:

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 Ado.net connection to the database, Ado.net is connected to the database with the SqlConnection, while MongoDB uses the Mongoclient connection and passes the connection characters in the constructor, which, of course, does not pass, so the default is to connect the local computer's defaults Identify the port (27017), such as the following three ways to connect:

var client = new Mongoclient ();

var client1 = new Mongoclient ("mongodb://localhost:27017");

var client2 = new Mongoclient ("mongodb://localhost:27017,localhost:27018,localhost:27019");

Get database

To get the database, you only need to call the Getdatabase method of the Mongoclient object, pass in the database name, and return directly if the database exists, or you will create the database and return, for example, the following code creates a database named "foo":

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

Now the database variable is pointing to the Foo databases.

Get linked List

Although 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");

Our incoming generic parameter is bsondocument, this is self-contained, can dynamically accommodate various formats of data, of course, here or recommend the reader to use Poco.

Insert a document

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

{
   ' name ': ' MongoDB ',
   ' type ': ' Database ',
   ' count ': 1,
   ' info ': {
     x:203,
     y:102
   }
}

Here we use the Bsondocument object to organize the JSON-formatted data above:

var document = new Bsondocument
{
  {"name", "MongoDB"},
  {"type", "Database"},
  {"Count", 1},
  { "Info", new bsondocument{
     {"X", 203},
     {"Y", 102}}}
;

Then we use the collection object's Insertoneasync to insert the above data into it:

Collection. Insertoneasync (DOC);

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

Insert Multiple Documents

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

var documents = Enumerable.range (0, 100). Select (x => new Bsondocument ("Counter", X));
Collection. Insertmanyasync (documents);

Statistics Number of documents

With the above steps we have inserted 101 data, and if we need to count the number of data in actual development, we can call the Countasync method, such as the following code:

var count = collection. Countasync (New Bsondocument ());
Console.WriteLine (count. result);

Query Chain List

Using the Find method, we can query the linked list and find method will return to our Ifindfluent<tdocument,tprojection> object, which belongs to the chain interface. So it can provide us with a chain like jquery to become a way to control query operations.

The first piece of data in the query list

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

var Firstdoc = collection. Find (New Bsondocument ()). Firstordefaultasync ();
Console.WriteLine (FirstDoc.Result.ToString ());

If the reader notices the final output, you will find a _id field, but we do not insert this field, this field is MongoDB automatically joined, I believe many people know its role, here is not to explain the amount of detail.

Query all data in a linked list

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

var documents = collection. Find (New Bsondocument ()). Tolistasync (). result;

For a small number of data, there is no problem with this approach, but if we need to deal with a lot of data, then we can't use the above method, we need to do it through Foreachasync, because this method executes a callback when each piece of data returns. To achieve the purpose of concurrent processing, such as the following code demonstrates how to use:

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

Querying a single piece of data by condition

We can call the Find method by passing in a filter condition 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 various conditional methods in the Builders static object filter, and then pass it on to the Find method.

Querying multiple data by criteria

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

var filter = Builders<bsondocument>. FILTER.GT ("Counter", m);
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", M) & filterbuilder.lt ("Counter");
Collection. Find (Filter). Foreachasync (x => Console.WriteLine (x));

Sort the data

Here we will add a sort on the basis of the query, sorting only need to call in the sort method when the corresponding parameters, such as the following example, we will query the list, 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;

Projecting on a field

Many times we don't need all the data in the document, it's like in SQL we just select the data we need, not all of the fields in the table, and natural mongodb can make me do it, We just need to use the projection constructor for filtering and sorting to construct and then pass it to the project method, and we'll exclude the "_id" field in the following example:

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, here are a few simple and commonly used update operations.

If we need to update an object (maybe 0 if the condition does not match), we can use the Updateoneasync method and execute the filter condition and the document that needs to be updated, for example, we update the "counter" in the "counter" 1 data to 110:

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

If we need batch updates, 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 as follows:

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

Delete Document

As the basic part of this is also the last part, use the above filter, and then call the Deleteoneasync or Deletemanyasync method, such as the following example is to delete "counter" is greater than 100 of all data:

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

So far, the foundation of MongoDB is over. Hope to help you learn, but also hope that we support the cloud-dwelling community.

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.