MongoDB learning notes (4) describe the data relationship using the document structure of MongoDB

Source: Internet
Author: User

The collection of MongoDB can be seen as a table of a relational database, and the document object can be seen as a record of a relational database. However, they are not completely equal. The table structure is fixed, and the MongoDB set does not have this constraint. In addition, the document objects stored in the set can even be embedded into sub-documents or "sub-sets ". In the end, they can all be described in a format similar to bjson. We will analyze the unique data management methods brought about by MongoDB today. We will take the samus driver as an example. The samus driver supports two ways to access the database: the basic method and the LINQ method. The basic method is described in the previous article, I don't want to explain the application examples separately in the way of LINQ. In this article, I will use two methods for comparison.

Series directory

MongoDB Study Notes (1) Introduction and installation of MongoDB
MongoDB Study Notes (2) use the samus driver to perform basic data operations
MongoDB learning notes (3) using jqgrid tables to operate MongoDB data in MVC Mode
MongoDB learning notes (4) describe the data relationship using the document structure of MongoDB
MongoDB Study Notes (5) MongoDB File Access Operations
MongoDB Study Notes (6) MongoDB index usage and Efficiency Analysis

1. Set Operations that contain sub-Documents

In such an application scenario, a website provides the member login function. Users must register an account to enjoy the membership service. However, the registrant may give up filling because the user data form input is too large, therefore, user information is divided into two types: primary information and detailed information. You only need to fill in the primary information for initial registration. We plan to design the details for sub-document storage.

1) implementation in the LINQ Mode

1. Create a data description class to describe user information

/// <Summary> /// main user information /// </Summary> public class userinfo {Public String userid {Get; set;} Public String username {Get; set;} Public String password {Get; set;} public detail {Get; Set ;}} /// <summary> /// user details /// </Summary> public class detail {Public String address {Get; set;} public int age {Get; set ;}public string email {Get; Set ;}}

2. Create a new user business operation class "userbll ". At this time, let the driver know the field information that the userinfo class describes "User Data". The configuration steps are implemented in the getmongo () method, and userbll is complete.CodeAs follows:

Public class userbll {Public String connectionstring = "MongoDB: // localhost"; Public String databasename = "mydatabase"; private Mongo; private relational database; // note that the generic type here is "userinfo" Private jsoncollection <userinfo> jsoncollection; Public userbll () {Mongo = getmongo (); Relational Database = Mongo. getdatabase (databasename) as your database; your collection = your database. getcollecti On <userinfo> () as your collection <userinfo>; Mongo. Connect ();}~ Userbll () {Mongo. disconnect () ;}/// <summary> // configure Mongo to map the class userinfo to the set /// </Summary> private Mongo getmongo () {var Config = new configurationbuilder (); config. mapping (mapping => {mapping. defaultprofile (profile => {profile. subclassesare (t => T. issubclassof (typeof (userinfo);}); mapping. map <userinfo> () ;}); config. connectionstring (connectionstring); return New Mongo (config. buildconfiguration ());}}

3. Next, define the method "insertsomedata ()" in the "userbll" class to insert some data:

/// <Summary> /// insert some data /// </Summary> Public void insertsomedata () {userinfo userinfo1 = new userinfo () {userid = "1001 ", username = "zhangsan", password = "123456"}; your collection. save (userinfo1); userinfo userinfo2 = new userinfo () {userid = "1002", username = "", password = "123456", detail = new detail () {address = "Hubei", age = 20, email = "lisi@163.com" }}; your collection. save (userinfo2); userinfo userinfo3 = new userinfo () {userid = "1003", username = "", password = "123456", detail = new detail () {address = "Guangdong", age = 20, email = "wangwu@163.com" }}; your collection. save (userinfo3); userinfo userinfo4 = new userinfo () {userid = "1004", username = "Zhao ", password = "123456", detail = new detail () {address = "Hubei" }}; your collection. save (userinfo4 );}

4. Define a Data Query Method "select", which will search for all users whose addresses are located in Hubei province in user details:

 
/// <Summary> /// the detailed information address is Hubei's user information // </Summary> public list <userinfo> select () {return condition collection. LINQ (). where (x => X. detail. address = "Hubei "). tolist ();}

5. Define a data deletion method to delete all data in the Set:

 
/// <Summary> /// delete all user information /// </Summary> Public void deleteall () {custom collection. Remove (x => true );}

6. Add the following code to the main method:

Static void main (string [] ARGs) {userbll = new userbll (); userbll. insertsomedata (); var users = userbll. select (); foreach (VAR user in users) {console. writeline (user. username + "Hubei") ;}; userbll. deleteall ();}

7. Final executionProgram, Print the following information:

 
Li Si is from Hubei, Zhao Liu is from Hubei.

1) general implementation

If you do not want to talk about the common implementation method, paste the Code directly to see what is the difference with the LINQ method:

Class program {static void main (string [] ARGs) {userbll = new userbll (); userbll. insertsomedata (); var users = userbll. select (); foreach (VAR user in users) {console. writeline (User ["username"]. tostring () + "Hubei") ;}; userbll. deleteall (); console. readline () ;}} public class userbll {Public String connectionstring = "MongoDB: // localhost"; Public String databasename = "mydatabase"; publi C string collectionname = "userinfo"; private Mongo; private relational database; private relational collection <document> relational collection; Public userbll () {Mongo = new Mongo (connectionstring); Relational Database = Mongo. getdatabase (databasename) as your database; your collection = your database. getcollection <document> (collectionname) as your collection <document>; Mongo. connect ();}~ Userbll () {Mongo. disconnect () ;}//< summary> /// insert some data /// </Summary> Public void insertsomedata () {document userinfo1 = new document (); userinfo1 ["userid"] = "1001"; userinfo1 ["username"] = "zhangsan"; userinfo1 ["password"] = "123456"; Collect collection. save (userinfo1); document userinfo2 = new document (); userinfo2 ["userid"] = "1002"; userinfo2 ["username"] = ""; userinfo2 ["password"] = "123456"; // subdocument var userinfo2detail = new document (); userinfo2detail ["Address"] = "Hubei "; userinfo2detail ["Age"] = 20; userinfo2detail ["email"] = "lisi@163.com"; userinfo2 ["detail"] = userinfo2detail; mongocollection. save (userinfo2); document userinfo3 = new document (); userinfo3 ["userid"] = "1003"; userinfo3 ["username"] = "Wang Wu "; userinfo3 ["password"] = "123456"; var userinfo3detail = new document (); userinfo3detail ["Address"] = "Guangdong"; userinfo3detail ["Age"] = 20; userinfo3detail ["email"] = "wangwu@163.com"; userinfo3 ["detail"] = userinfo3detail; detail collection. save (userinfo3); document userinfo4 = new document (); userinfo4 ["userid"] = "1004"; userinfo4 ["username"] = "Zhao "; userinfo4 ["password"] = "123456"; var userinfo4detail = new document (); userinfo4detail ["Address"] = "Hubei"; userinfo4 ["detail"] = userinfo4detail; collections collection. save (userinfo4); }/// <summary> // query the detailed information address. The address is Hubei user information /// </Summary> Public ienumerable <document> select () {return response collection. find (new document {"detail. address "," Hubei "}}). documents;} /// <summary> /// delete all user information /// </Summary> Public void deleteall () {your collection. remove (new document {});}}

Finally, we use this code to output the bjson format of all user information:

 
/// <Summary> /// print data bjson /// </Summary> Public void printbjson () {string bjson = string. empty; foreach (VAR grouping et in grouping collection. findall (). documents) {bjson + = paiet. tostring ();} console. writeline (bjson );}

The result is as follows:

{"Userid": "1001", "username": "Zhang San", "password": "123456", "_ id": "4d80ec1ab8a4731338000001"} {"userid ": "1002", "username": "Li Si", "password": "123456", "detail": {"Address": "Hubei", "Age": 20, "email": "lisi@163.com"}, "_ id": "4d80ec1ab8a473133811602"} {"userid": "1003", "username": "Wang Wu", "password ": "123456", "detail": {"Address": "Guangdong", "Age": 20, "email": "wangwu@163.com"}, "_ id ": "4d80ec1ab8a473133820.03"} {"userid": "1004", "username": "Zhao six", "password": "123456", "detail": {"Address ": "Hubei"}, "_ id": "4d80ec1ab8a4731338000004 "}
2. Set Operations that contain "subsets"

For example, a school's personnel management system collects information about classes and students, and now defines a "class set ", the student field in this set is a "student set" that contains all the students in this class.

1) implementation in the LINQ Mode

I will not talk about the basic configuration. The data class is defined as follows:

/// <Summary> // class information /// </Summary> public class classinfo {Public String classname {Get; set;} public list <student> students {Get; set ;}//< summary> /// student information /// </Summary> public class student {public string name {Get; set ;} public int age {Get; Set ;}}

Query the class of a student named "Zhang San" and his details:

(This is actually in the memory after tolist. It seems that the driver does not support direct query in the LINQ method .)

 
Public list <classinfo> select () {return collections collection. LINQ (). tolist (). where (x => X. students. exists (S => S. name = "James ")). tolist ();}

1) general implementation

Query the class of a student named "Zhang San" and his details:

Public list <document> select () {var collections collection = relational database. getcollection ("classinfo"); return response collection. find (new document {"students. name "," James "}}). documents. tolist ();}

Print the bjson data:

 
{"_ Id": "4d814bae5c5f000000005f63", "classname": "1001", "Students": [{"name": "James", "Age": 10 }, {"name": "", "Age": 0}]} {"_ id": "4d814bae5c5f0000000000005f64", "classname": "1002", "Students ": []} {"_ id": "4d814bae5c5f000000005f65", "classname": "1003", "Students": [{"name": "Wang Wu", "Age ": 11 },{ "name": "Zhao Liu", "Age": 9}]}
Iii. Summary

Through this example, we found that MongoDB has a unique document structure that can describe some relationship features between data objects. Although it does not support multi-table queries that are as powerful as querying between tables in relational databases, it can also describe more flexible relational features through the document structure. In this case, what a relational database can do is, mongoDB can basically do the same. Even some relational databases are not easy to do, So MongoDB can easily do it, such as describing the inheritance relationships of data classes.

By Lipan)
Source: [Lipan] (http://www.cnblogs.com/lipan)
Copyright: The copyright of this article is shared by the author and the blog. The detailed link of this article must be noted during reprinting; otherwise, the author will be held legally liable.
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.