Recently, nosql databases are very popular, so I started to learn MongoDB with the attitude of keeping pace with the times. The best way to learn is to manually make an instance, so I chose the frequently used tree structure as an example for getting started. In this example, the tree structure is constructed based on the full path method recommended by tree in MongoDB.
The first thing to do is the operation page shown in Figure 1.
Figure 1 operation page
The operation page is very simple. It is to create a tree structure using the tree control of Ext, and add or delete the tree using the small buttons on the control. Click the node Text of the Tree node to modify it. Because the focus of this article is not the ext interfaceCodeYou can download it if you are interested.Source code.
The following describes how to operate the MongoDB background code. First, define a class according to the tree structure. The class definition is as follows:
Public class node { Public objectid ID { Get ; set ;}< span style =" color: # 0000ff "> Public string title { Get ; set ;}< span style =" color: # 0000ff "> Public int depth { Get ; set ;}< span style =" color: # 0000ff "> Public string path { Get ; set ;}
From the class definition, we can see that the storage structure of the Tree node mainly has four items: ID is a unique number, title is the node name, and depth is the depth of the node, PATH is the full path of the node.
The following describes the subnode query operations. The Code is as follows:
Private String List (httpcontext context ){ String Nodeid = context. Request. Params [" Node "] ??? " "; Jarray ja = New Jarray (); Using (VAR Mongo = Mongo. Create (" MongoDB: // 192.168.0.77/trees ") {Var nodes = Mongo. getcollection <node> (" Node "); If (Nodeid =" "| Nodeid =" Rootnode ") {Var q = nodes. Find ( New {Depth = 0 }); Foreach (VAR C In Q) {Ja. Add ( New Jobject ( New Jproperty (" ID ", C. Id. tostring ()), New Jproperty (" Text ", C. Title ), New Jproperty (" Leaf ", False )));}} Else {Node = nodes. findone ( New {_ Id = New Objectid (nodeid )}); If (Node! = Null ) {Var q = nodes. Find ( New {Path = New RegEx (" ^ "+ Node. Path), depth = node. Depth + 1 }); Foreach (VAR C In Q) {Ja. Add ( New Jobject ( New Jproperty (" ID ", C. Id. tostring ()), New Jproperty (" Text ", C. Title ), New Jproperty (" Leaf ", False )));}}}} Return Ja. tostring ();}
In the code of the list method, the first line is to obtain the parent node ID. The role of Jarry object ja is to return the subnode array. Note the following:
Using(VAR Mongo = Mongo. Create ("MongoDB: // 192.168.0.77/trees"))
We recommend that you use the using keyword here. The main reason is to allow the object to automatically release the connection. Otherwise, when the operation is frequent, "norm. mongo exception: Connection timeout trying to get connection from connection pool "error. During debugging, I was troubled for some time.
In someArticleI will use new MongoDB to connect to the database. What is the difference? I did not study it carefully. The create method is used to draw a gourd Based on the norm test example. This can be selected based on your habits. If the MongoDB port is different, you can add the port number after the IP address. For example, if the port number is 10000, you can modify the Code as follows:
Using(VAR Mongo = Mongo. Create ("MongoDB: /// 192.168.0.77: 10000/trees"))
The "Trees" in the connection string is the name of the database to be connected.
The following is a collection of data from the database. If you want to return the child node of the root node, you can directly search for the node whose depth is 0. Otherwise, you must first obtain the parent node through the findone method, and then use the path of the parent node to query its child nodes through a regular expression. Here, because the returned result is only a subnode of the next level of the parent node, you need to add a node depth condition (depth = node. Depth + 1 ).
The code for the add method is used to add Tree nodes:
Private String Add (httpcontext context ){ String Output =" "; String Title = context. Request. Params [" Value "] ??? " "; If (Title. length> 0 ){ String Nodeid = context. Request. Params [" Parentid "] ??? " "; Using (VAR Mongo = Mongo. Create (" MongoDB: // 192.168.0.77/trees ") {Var nodes = Mongo. getcollection <node> (" Node "); Var node = New Node (); node. ID = objectid. newobjectid (); node. Title = title; node. Depth = 0; node. Path = node. ID +" , ";If (Nodeid. length> 0) {node q = nodes. findone ( New {_ Id = New Objectid (nodeid )}); If (Q! = Null ) {Node. Depth = Q. Depth + 1; node. Path = Q. Path + node. ID +" , ";}} Nodes. insert (node); Output = ( New Jobject { New Jproperty ("Success ", True ), New Jproperty (" Data ", New Jobject ( New Jproperty (" ID ", Node. Id. tostring ()), New Jproperty (" Text ", Node. Title ), New Jproperty (" Leaf ",False )}). Tostring ();}} Else {Output = ( New Jobject { New Jproperty (" Success ", False ), New Jproperty (" Data "," Enter a node name. ")}). Tostring ();} Return Output ;}
It is easy to add a subnode. You only need to create a Node object and save it by using the inser method. By default, the newly created Node object is a top-level node. If the parent node exists, modify the depth and path attributes of the Node object.
The code for the del method is as follows:
Private String Del (httpcontext context ){ String Output =" "; String Id = context. Request. Params [" ID "] ??? " "; If (Id. length> 0 ){Using (VAR Mongo = Mongo. Create (" MongoDB: // 192.168.0.77/trees ") {Var nodes = Mongo. getcollection <node> (" Node "); Node q = nodes. findone ( New {_ Id = New Objectid (ID )}); If (Q! = Null ) {Nodes. Delete ( New {Path = New RegEx (" ^ "+ Q. Path)}); Output = ( New Jobject { New Jproperty (" Success ", True ), New Jproperty (" Data ", ID)}). tostring ();} Else {Output = ( New Jobject { New Jproperty ("Success ", False ), New Jproperty (" Data "," The node to be deleted does not exist or has been deleted! ")}). Tostring ();}}} Else {Output = ( New Jobject { New Jproperty (" Success ", False ), New Jproperty (" Data "," Select the node to delete! ")}). Tostring ();} Return Output ;}
Because the full path structure is used, it is quite easy to delete a node and its sub-nodes. You only need to use the full path of the node to search for the node itself and its sub-nodes using a regular expression. In this example, you can use the following statement to easily delete a file:
Nodes. Delete (New{Path =NewRegEx ("^"+ Q. Path )});
The code for the Edit Method is as follows, which is used to modify the node name:
Private String Edit (httpcontext context ){ String Output =" "; String Id = context. Request. Params [" ID "] ??? " "; String Title = context. Request. Params [" Value "] ??? " "; If (Title. length> 0 ){ If (Id. length> 0 ){Using (VAR Mongo = Mongo. Create (" MongoDB: // 192.168.0.77/trees ") {Var nodes = Mongo. getcollection <node> (" Node "); Node q = nodes. findone ( New {_ Id = New Objectid (ID )}); If (Q! = Null ) {Q. Title = title; nodes. Save (Q); Output = ( New Jobject {New Jproperty (" Success ", True ), New Jproperty (" Data ", ID)}). tostring ();} Else {Output = ( New Jobject { New Jproperty (" Success ", False ),New Jproperty (" Data "," The node to be modified does not exist or has been deleted! ")}). Tostring ();}}} Else {Output = ( New Jobject { New Jproperty (" Success ", False ), New Jproperty (" Data ","The node to be modified does not exist or has been deleted! ")}). Tostring ();}} Else {Output = ( New Jobject { New Jproperty (" Success ", False ), New Jproperty (" Data "," Enter a node name! ")}). Tostring ();} Return Output ;}
In the code, you must first determine whether the name of the submitted node is null. If it is not empty, continue to judge whether the submitted node ID is correct. Then you need to use the findone method to search for the node, after modifying the title attribute, save it as needed.
The example has been completed. From the example, it can be seen that using norm to operate MongoDB is quite convenient and the code is very concise.
The example shows that using the full path method, it is quite convenient to create a stepless tree in MongoDB, because the path is not restricted by the length of the database field, however, if you consider the MongoDB storage size, it is estimated that it is also a problem, but this is to be tested. This is also an advantage of nosql databases.
Source code: http://download.csdn.net/source/2652662