Getting Started with MongoDB for C# Basics

The author uses the .net driver recommended by the mongoDB official website:

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

Readers about the installation of MongoDB can refer to other blogs, and there is no need for too much configuration for basic learning.

 

Create a connection

This step is the same as that of ADO.NET connecting to the database. ADO.NET uses SqlConnection to connect to the database, while MongoDB uses MongoClient to connect and pass the connection character in the constructor. Of course, it can not be passed, then the default It is the default port (27017) for connecting to the local computer, such as the following three connection methods:

copy code
1 var client = new MongoClient();
2
3 var client1 = new MongoClient("mongodb://localhost:27017");
4
5 var client2 = new MongoClient("mongodb://localhost:27017,localhost:27018,localhost:27019");
copy code

 

 

get database

In order to get the database, you only need to call the GetDatabase method of the MongoClient object and pass in the database name. If the database exists, it will be returned directly. Otherwise, the database will be created and returned. For example, the following code will create a database named "foo". database:

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

The database variable now points to the foo database.

 

get linked list

Although it is called getting a linked list, it is actually getting a table in the database. We can get it through the GetCollection<TDocument> method of the database above. For example, in the following code, we will get a table named "bar":

var collection = database.GetCollection<BsonDocument>("bar");

The generic parameter we pass in is BsonDocument , which is built-in and can dynamically accommodate data in various formats. Of course, readers are recommended to use POCO.

 

insert a document

Using the collection object, we can insert documents into it, such as the following json format data:

copy code
{
     "name": "MongoDB",
     "type": "database",
     "count": 1,
     "info": {
         x: 203,
         and: 102
     }
}
copy code

Next we use the BsonDocument object to organize the data in the JSON format above:

copy code
var document = new BsonDocument
{
    {"name","MongoDB"},
    {"type","Database"},
   {"count",1},
   {"info",new BsonDocument{
         {"x",203},
         {"y",102}
       }
   }
};
copy code

Then we use the InsertOneAsync of the collection object to insert the above data into it:

collection.InsertOneAsync(doc);

We all know that the methods with Async as the suffix support asynchronous, but the author is demonstrating it in the console project, so this await is not added. If the reader is testing in other environments, it can be added according to the situation.

 

Insert multiple documents

If we need to insert multiple documents at one time, we can use the InsertManyAsync method. For example, in the following example, we will insert 100 pieces of data:

var documents = Enumerable.Range(0, 100).Select(x => new BsonDocument("counter", x));
collection.InsertManyAsync(documents);

 

 

Count the number of documents

Through the above steps, we have inserted 101 pieces of data. 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 linked list

Using the Find method, we can query the linked list, and the Find method will return us the IFindFluent<TDocument, TProjection> object, which belongs to the chain interface, so it can provide us with a chain like jquery to control the query operation.

 

Query the first data of the linked list

In order to get the first piece of data, we can call the FirstOrDefaultAsync method, which will return the first piece of data. If there is no data, it will return null. For example, the following code will display the first piece of data in the linked list:

var firstDoc = collection.Find(new BsonDocument()).FirstOrDefaultAsync();
Console.WriteLine(firstDoc.Result.ToString());

If readers pay attention to the final output, they will find an _id field, but we did not insert this field. This field is automatically added by mongoDB. I believe many people know its function, so I will not explain it in detail here.

 

Query all data in linked list

If you want to return all the data in the linked list, you can call the ToListAsync method after the Find operation, and the result of the type List<T> will be returned directly, such as the following code:

var documents = collection.Find(new BsonDocument()).ToListAsync().Result;

In the case of a small amount of data, the above method is no problem, but if we need to process a large amount of data, then we cannot use the above method, we need to use the following method to complete it through ForEachAsync , because This method will execute a callback when each piece of data is returned, so as to achieve the purpose of concurrent processing. For example, the following code demonstrates how to use it:

collection.Find(new BsonDocument()).ForEachAsync(x => Console.WriteLine(x));

 

 

Query a single piece of data by condition

We can pass in a filter condition when calling the Find method to query the data we want in the linked list. For example, in the following example, we will query the data with the value of 71 in the field "counter" :

var filter = Builders<BsonDocument>.Filter.Eq("counter", 71);
var document = collection.Find(filter).FirstAsync().Result;
Console.WriteLine(document);

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

 

Query multiple pieces of data by condition

We can also get multiple pieces of data. For example, in the following example, we will search for all data whose "counter" value is greater than 50:

var filter = Builders<BsonDocument>.Filter.Gt("counter", 50);
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", 50) & filterBuilder.Lt("counter", 70);
collection.Find(filter).ForEachAsync(x => Console.WriteLine(x));

 

 

Sort data

Next, we will add sorting on the basis of the query. The sorting only needs to pass in the corresponding parameters when calling the Sort method. For example, in 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;

 

 

cast on field

Many times we don't need all the data in the document. This is like in SQL, we will only select the data we need, but not all the data in the fields in the table. Naturally, MongoDB can also let me To do this, we just need to use the Projection constructor to construct and pass it to the Project method like filtering and sorting. 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 documentation

MongoDB has many update operations. Below we will introduce a few simple and commonly used update operations.

 

If we need to update an object (if the conditions do not match, it may be 0) , we can use the UpdateOneAsync method, and execute the filter conditions and the documents that need to be updated, such as "counter" in the data where we set "counter" to 1 below Update to 110:

var filter = Builders<BsonDocument>.Filter.Eq("counter", 1);
var updated = Builders<BsonDocument>.Update.Set("counter", 110);
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 whose " counter" is less than 10 , then we can write it as follows:

var filter = Builders<BsonDocument>.Filter.Lt("counter", 10);
var updated = Builders<BsonDocument>.Update.Inc("counter", 100);
var result = collection.UpdateManyAsync(filter, updated).Result;

 

 

delete document

As the basic part, this is the last part. Use the above filtering, and then call the DeleteOneAsync or DeleteManyAsync method. For example, the following example is to delete all data with "counter" greater than 100:

var filter = Builders<BsonDocument>.Filter.Gt("counter", 100);
var resut = collection.DeleteManyAsync(filter).Result;

 

 

 

So far, the basic part of MongoDB is over.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325247655&siteId=291194637