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 is using SqlConnection to connect to the database, while MongoDB uses the Mongoclient connection, and in the constructor to pass the connection character in, of course, can not be passed, then the default is to connect to the local computer Port (27017), such as the following three connection modes:
1 var client = new Mongoclient (), 2 3 var client1 = new Mongoclient ("mongodb://localhost:27017"), 4 5 var client2 = new Mong OClient ("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 = new bsondocument{ {"Name", "MongoDB"}, {"type", "Database"}, {"Count", 1}, {"Info", new bsondocument{ {"X", 203}, {"Y", 102}}} ;
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 (0, 100). Select (x = 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 ("Counter", 1); 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, such as the following example is to delete "counter" all data greater than 100:
var filter = Builders<bsondocument>. FILTER.GT ("Counter"), var Resut = collection. Deletemanyasync (filter). Result;
So far, the basic part of MongoDB is over.
Getting Started with MongoDB for C # basics