MongoDB combat Development "0 basic Learning, with complete ASP.
Read Catalogue
- Begin
- Download MongoDB, and start it
- Using MongoDB in C #
- Refactoring (simplifying) code
- Viewing data using MongoDB's clients
- Maintaining data using MongoDB's clients
- The C # driver provided by MongoDB
- MongoDB does not support the use of join operations when querying a database
- Get MongoDB Server State
"Goal": This article will show you how to access MongoDB in C #, complete common database operations tasks, and also introduce MONGODB clients (command-line working mode) and some basic commands in the form of real combat.
"description": What is MongoDB? What's the use? If you don't know these questions, please Google yourself.
"Fit Object": A C # developer who has no contact with MongoDB or a little understanding of MongoDB. So this article is an entry-level article.
Sample project: The complete example of this article is a simple "customer, commodity, order" business scenario, click here (but not exactly the same) for the preview interface effect, and also include the source code to download the sample project.
Let's start the actual introduction of MongoDB.
Go back to the top and download MongoDB and start it
You can download to mongodb:http://www.mongodb.org/downloads at this address, this article will be "MONGODB-WIN32-I386-1.8.2-RC2" to demonstrate the use of MongoDB.
Are you ready to download? Let's go ahead. Please unzip the zip archive of the MongoDB you just downloaded and go to the unpacked Bin directory, and you will find a bunch of exe files. Now, open the command-line window and switch to the bin directory you just made, and then enter the following command:
Here, I run the program Mongod.exe, and tell it the data File save directory (this directory to be created beforehand), as for the Mongod more command line parameters, enter the command: Mongod/? To obtain.
If you also see this interface, then the service side of MongoDB has started successfully.
By the way: After running Mongod, it will display some useful information. For example: PID (Process ID), TCP port (listening port), HTTP ports (for viewing the running status), operating system version, data directory, or 64-bit version, if it is a 32-bit version, it will also tell you "data has a 2G limit", so the official use of the recommendation to run the 64-bit version.
Next, we're going to download MongoDB's C # driver, which allows us to use MongoDB in C #. : Https://github.com/samus/mongodb-csharp
The compressed package I downloaded is: Samus-mongodb-csharp-0.90.0.1-93-g6397a0f.zip. This compression package itself also contains a sample, interested to see it.
The driver we need to access MongoDB in C # is the project MongoDB. Compile this project to get it, file name: MongoDB.dll
Back to top in C # using MongoDB
Well, with the preparatory work ahead, we can start using MongoDB in C #. However, because there is a lot of code for this sample project, this article will show only the relevant code that interacts with MongoDB, and the more complete code should consult the sample project itself.
Next, this article shows some basic data operations for "customer profile" through C #, or the first to define a type of customer profile.
public sealed class Customer
{
[MongoId]
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public string ContactName { get; set; }
public string Address { get; set; }
public string PostalCode { get; set; }
public string Tel { get; set; }
}
Description: This is a simple class, and [MongoId] in the code is also not allowed (after that).
Before operating the database, I want to explain: MongoDB before use, do not require you to create the corresponding database, design data table Structure!
In MongoDB, there is no "table" concept, instead of "set", there is no "data logging" concept, instead of "document", we can understand the "document" as an "object", arbitrary objects, even can have complex nesting level.
Therefore, we do not have to write code from the "table field" to the C # class "Attribute, field" conversion, and now directly read and write to the entire object.
And MongoDB does not support join operations, so if you have an "association" operation, you need to handle it yourself.
Then define two variables:
private static readonly string _connectionString = "Server=127.0.0.1";
private static readonly string _dbName = "MyNorthwind";
New record
Public void Insert(Customer customer)
{
customer.CustomerID = Guid.NewGuid().ToString("N");
// First create a connection
Using( Mongo mongo = new Mongo(_connectionString) ) {
// open the connection
mongo.Connect();
/ / Switch to the specified database
Var db = mongo.GetDatabase(_dbName);
/ / Get the corresponding collection according to the type
Var collection = db.GetCollection<Customer>();
// Insert an object into the collection
collection.Insert(customer);
}
}
In the code above, each line has a comment, and this is no longer explained.
Deleting records
Public void Delete(string customerId)
{
Using( Mongo mongo = new Mongo(_connectionString) ) {
mongo.Connect();
Var db = mongo.GetDatabase(_dbName);
Var collection = db.GetCollection<Customer>();
// Remove the specified object from the collection
collection.Remove(x => x.CustomerID == customerId);
}
}
Update record
Public void Update(Customer customer)
{
Using( Mongo mongo = new Mongo(_connectionString) ) {
mongo.Connect();
Var db = mongo.GetDatabase(_dbName);
Var collection = db.GetCollection<Customer>();
// update the object
collection.Update(customer, (x => x.CustomerID == customer.CustomerID));
}
}
Get a list of records
Public List<Customer> GetList(string searchWord, PagingInfo pagingInfo)
{
Using( Mongo mongo = new Mongo(_connectionString) ) {
mongo.Connect();
Var db = mongo.GetDatabase(_dbName);
Var collection = db.GetCollection<Customer>();
// Create a query first
Var query = from customer in collection.Linq()
Select customer;
/ / Increase query filter conditions
If( string.IsNullOrEmpty(searchWord) == false )
Query = query.Where(c => c.CustomerName.Contains(searchWord) || c.Address.Contains(searchWord));
// Sort by name first, then return to paged results.
Return query.OrderBy(x => x.CustomerName).GetPagingList<Customer>(pagingInfo);
}
}
Get a single object
Public Customer GetById(string customerId)
{
Using( Mongo mongo = new Mongo(_connectionString) ) {
mongo.Connect();
Var db = mongo.GetDatabase(_dbName);
Var collection = db.GetCollection<Customer>();
/ / Query a single object
Return collection.FindOne(x => x.CustomerID == customerId);
}
}
Back to top refactoring (Simplified) code
As can be seen from the above code, Operation MongoDB is basically such an operation process.
// First create a connection
Using( Mongo mongo = new Mongo(_connectionString) ) {
// open the connection
mongo.Connect();
/ / Switch to the specified database
Var db = mongo.GetDatabase(_dbName);
/ / Get the corresponding collection according to the type
Var collection = db.GetCollection<Customer>();
// [Access collection, do what you want to do]
}
To solve this problem, I provide a wrapper class to simplify the use of MongoDB.
The simplified crud code is as follows:
public void Insert(Customer customer)
{
customer.CustomerID = Guid.NewGuid().ToString("N");
using( MyMongoDb mm = new MyMongoDb() ) {
mm.GetCollection<Customer>().Insert(customer);
}
}
public void Delete(string customerId)
{
using( MyMongoDb mm = new MyMongoDb() ) {
mm.GetCollection<Customer>().Remove(x => x.CustomerID == customerId);
}
}
public void Update(Customer customer)
{
using( MyMongoDb mm = new MyMongoDb() ) {
mm.GetCollection<Customer>().Update(customer, (x => x.CustomerID == customer.CustomerID));
}
}
public Customer GetById(string customerId)
{
using( MyMongoDb mm = new MyMongoDb() ) {
return mm.GetCollection<Customer>().FindOne(x => x.CustomerID == customerId);
}
}
Looking at the above code, you should think MongoDB is very easy to use, right.
Next, I will enter some data through the interface, to see the results of my input.
Here, you might want to know: does MongoDB have a client of its own to view the data? Because you can't just rely on yourself to write code to see the data?
Yes, MongoDB also provides a client to view and maintain the database. Next, let's take a look at how to use the MongoDB client.
Back to the top using MongoDB client to view data
MongoDB comes with a JavaScript shell that can interact with the MongoDB instance from the command line. This shell can be useful for managing operations, checking running instances, querying data, and so on.
Let's go back to the command-line window mode (no way, MongoDB only provides this interface), run Mongo.exe, such as
This is the command-line mode of the MongoDB client. Usually we switch to "current data" before we operate the database,
MongoDB is the same, we can run the following command to view the list of databases, and switch the database, and then view the collection list, see (I ran three commands)
Note: MongoDB distinguishes the case of a name.
In MongoDB, look at the current database, you can use the command "DB",
View the total number of records for the collection customer: "DB. Customer.count (); "
View the record for CustomerId = 1: "DB. Customer.findone ({"_id": "1"}); ", note: The query condition is a document, which is the feature of MongoDB.
Shows the execution result of the above three commands:
Well, how did it get garbled? CustomerId = 1 The record is supposed to be like this.
See this scene, you should not suspect that MongoDB is wrong, this error is due to MONGODB client using encoding is UTF-8, and Windows command-line program cmd.exe use GB2312 (I currently use Chinese language) caused.
Workaround:
1. Execute MongoDB's "exit" command back to the Windows command line State (or reopen the command-line window),
2. Run the command: "chcp 65001", switch to the UTF-8 encoding to work.
3. Set the properties of the command-line window, refer to:
Then run MONGO into the MONGO command line, switch the database, and execute the command: "DB." Customer.findone ({"_id": "1"}); "
Now you can see that the Chinese characters are displayed normally, but finally it shows "Failed to write to logfile", for this problem, if we execute the command "db." Customer.findone ({"_id": "91"}); "(Id=91 's record is my last entry, all A's that, the front has), can be found that no anomalies occurred, so that the problem is still related to cmd.exe. If you switch back to CHCP 936, you will see garbled characters, but there is no "Failed to write to logfile", so I will ignore this error.
Back to the top using MongoDB client to maintain data
Let me show you how to use the client of MongoDB to perform some basic data maintenance functions. Let's start with crud operations, see, for convenience, I'll execute multiple commands in one.
Note: MongoDB's documentation uses an object called the Bson format, similar to JSON in JavaScript.
In the example above, after each command, I added a red circle. In the example, I switch to the MyTest database first (it doesn't exist, but it doesn't matter), and then I define a document item and insert it into the collection table1, and then define a document ITEM2, also inserted into the collection table1. Note: item, ITEM2 's structure is completely different, but can be placed in a collection (not recommended). The last call to find () displays all the documents in the collection.
At this point, did you notice that "each document has a member named" _id ", which I don't define.
In fact, MongoDB will create such a document for each document member, we specify the "key", "id" for MongoDB: They are not "the primary key of the document", MongoDB only recognized "_id", you can specify, but if not specified, MongoDB is automatically added.
At this point, you can look at the first two pictures, you can see: When defining the Customer class, there is a member CustomerID at this time does not exist! We can look at the definition of customer again:
public sealed class Customer
{
[MongoId]
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public string ContactName { get; set; }
public string Address { get; set; }
public string PostalCode { get; set; }
public string Tel { get; set; }
}
At this point, you should find that the CustomerID member has a [MongoId] feature. Because of this feature, the driver will map CustomerID to "_id" for use.
OK, back to the command line again, I'm going to show the other commands. Please see:
To update a document, we use the FindOne () method to locate the document object to be modified, save it in a variable T, modify its properties, and then call the update () method to update the document, noting that when you call Update (), the first parameter "update range" is given in the form of a document, and the second parameter is the new object to be updated. When deleted, the delete condition is also specified in the form of a document. Use the documentation everywhere, which is the feature of MongoDB.
In the previous example code, I used Find () and FindOne (), which are different: FindOne () returns only one Document object, find () returns a list of collections, and if you do not specify a filter range, it returns the entire collection, but only the top 20 documents are displayed in the client.
A more complex query: The search date range is the order record from 2011-06-25 to 2011-06-26. Because the results returned are too long, I will not show them.
Note: MongoDB query conditions, and no <, >=, <= these operators, but use "$lt", "$lte", "$gt", "$gte" this way as a document key to use, so a simple OrderDate >= "2006-06-25" and OrderDate < "2006-06-26" are written in the following ways:
If you encounter or are more troublesome, such as: CustomerId = 1 or CustomerId = 2, there are two ways:
The grammar is not difficult, believe that can read the JSON person, also can understand these two commands.
A second paging command:
Similar to the syntax of LINQ, good understanding.
The MongoDB client also supports other syntaxes, which are not described here. Because our goal is to use MongoDB in C #, in the C # driver provided by MongoDB, we do not need to write such troublesome query conditions, just need to write the query in LINQ syntax, so it will be easy to use. However, some maintenance operations, we can only be executed by command, such as: Delete the collection, delete the database.
Execute "db.runcommand ({" Drop ":" Table1 "});" You can delete a collection or execute the command "Db.table1.drop ();", the effect is the same.
Let's look at the commands for how to delete a database:
Note: the command "Db.runcommand ({" Dropdatabase ": 1});" Can only delete the current database, so to switch the current database, and then execute this command, execute the command to delete the database, we then use the command "show DBS;", Discover the database " MyTest "No longer exists, that is, the deletion succeeded. There is one more way to delete a database: Remember when I first started Mongod.exe, I passed a parameter "-dbpath" H:\AllTempFiles\mongodb\data ""? Let's go to that directory and see what's in there.
Look at this picture, you have not thought: these two "MyNorthwind" the beginning of the file will be the database? I'm going to delete it now, stop Mongod.exe, and then delete the file (since I currently have only one database, I have deleted all the files under the directory), after deletion:
Now, I'll start Mongod.exe and then execute the command on the client "show DBS;" Look at:
Now we can find that our previous "MyNorthwind" Database is gone, and of course it is deleted. Note: Now these two databases are MongoDB's own, for special purposes, we can ignore them.
Well, let's see what the C # driver from MongoDB provides.
Back to top MongoDB provided by C # driver
I have made a class that is considered more important in the C # driver provided by MongoDB:
Let's take a look at the code in front of me that operates MongoDB:
// First create a connection
Using( Mongo mongo = new Mongo(_connectionString) ) {
// open the connection
mongo.Connect();
/ / Switch to the specified database
Var db = mongo.GetDatabase(_dbName);
/ / Get the corresponding collection according to the type
Var collection = db.GetCollection<Customer>();
// [Access collection, do what you want to do]
}
This code roughly illustrates a process of manipulating MongoDB in C #, mainly involving the first three classes, which are the core classes of the three classes. It is worth mentioning that: the Linqextensions.linq () method allows us to easily use Linq's elegant syntax when writing queries, rather than a bunch of complex document conditions! That's why I chose this driver.
Remember how several examples of calling RunCommand at the command line were in front of me? If you also need to do this in C #, you can call the Mongodatabase.sendcommand () method. For example: Delete Collection category, we can write:
void DeleteCategoryCollection()
{
using( MyMongoDb mm = new MyMongoDb() ) {
mm.CurrentDb.SendCommand(new Document("drop", "Category"));
}
}
"Mongoidattribute": lets you map a data member of a C # class to the document's "_id" property. There is an example here that says no more.
"Mongoaliasattribute": allows us to map the data members of a C # class to other property names when mapping to a document.
For example: I want to save CustomerName members to MongoDB using a CNAME.
[Mongoalias ("CName")]public string CustomerName {get; set;}
"Mongoignoreattribute": You can have a C # class ignore certain Members when it is saved to MongoDB. Take a look at the following code:
Public sealed class OrderItem : MyDataItem
{
[MongoId] // This member will be mapped to "_id"
Public string OrderID { get; set; }
[ScriptIgnore] // Ignore this member when serializing JSON
Public DateTime OrderDate { get; set; }
[MongoIgnore] // Ignore this member when saving to MongoDB
Public string CustomerName { get; set; }
// .... There are other properties.
// Add this property just to make it easier to display in the client, otherwise the client handles the format conversion is really troublesome.
// It will not be written to the database.
[MongoIgnore]
Public string OrderDateText { get { return this.OrderDate.ToString("yyyy-MM-dd HH:mm:ss"); } }
}
Back to top MongoDB does not support the use of join operations when querying the database
In MongoDB, a document is a complete object, so when you get an object, you don't need the kind of join syntax for the relational database. In the OrderItem defined above, CustomerName is not saved to the database, but at the time of loading, using the "reference" design method, according to CustomerID to access the collection of customer to obtain the corresponding CustomerName, This is also a common usage scenario for joins.
There is a requirement in the sample project: To query the list of orders based on a date range (support paging). This is how I implemented the query.
/// <summary>
/// Get a list of order records based on the specified query date range and paging parameters
/// </summary>
/// <param name="dateRange">date range</param>
/// <param name="pagingInfo">Page Parameters</param>
/// <returns>order record list</returns>
Public List<OrderItem> Search(QueryDateRange dateRange, PagingInfo pagingInfo)
{
dateRange.EndDate = dateRange.EndDate.AddDays(1);
Using( MyMongoDb mm = new MyMongoDb() ) {
Var collection = mm.GetCollection<OrderItem>(STR_Orders);
Var query = from ord in collection.Linq()
Where ord.OrderDate >= dateRange.StartDate && ord.OrderDate < dateRange.EndDate
Orderby ord.OrderDate descending
Select new OrderItem {
OrderID = ord.OrderID,
CustomerID = ord.CustomerID,
OrderDate = ord.OrderDate,
SumMoney = ord.SumMoney,
Finished = ord.Finished
};
// Get the list of orders, which will return results that match the page.
List<OrderItem> list = query.GetPagingList<OrderItem>(pagingInfo);
// Get all the customer IDs in the order list
String[] cids = (from ord in list
Where string.IsNullOrEmpty(ord.CustomerID) == false
Select ord.CustomerID)
.Distinct()
.ToArray();
// find all customer records
Dictionary<string, Customer> customers =
(from c in mm.GetCollection<Customer>().Linq()
Where cids.Contains(c.CustomerID)
Select new Customer {
CustomerID = c.CustomerID,
CustomerName = c.CustomerName
})
.ToDictionary(x => x.CustomerID);
// Set the CustomerName for the order list result
Foreach( OrderItem ord in list ) {
Customer c = null;
If( string.IsNullOrEmpty(ord.CustomerID) == false && customers.TryGetValue(ord.CustomerID, out c) )
ord.CustomerName = c.CustomerName;
Else
ord.CustomerName = string.Empty;
}
Return list;
}
}
Back to top get MongoDB server state
Let's take a look at the screenshot that started the server:
Notice the last line, it tells us it has a web interface, the port is 28017, and now I'm going to see what it looks like.
You can see that it provides some status information on the server side. We can also get a JSON-based statistic by accessing "Http://localhost:28017/_status".
We can also get this information by running the command "Db.runcommand ({" Serverstatus ": 1}) of the client:
MongoDB combat Development "0 basic Learning, with complete ASP.