MongoDB Learning Notes (iv) describing data relationships with MongoDB document structure _ server other

Source: Internet
Author: User
Tags mongodb relational database table

MongoDB Collections (collection) can be viewed as tables of relational databases, and document objects (documents) can be viewed as a record of relational databases. But the two are not exactly equal. The structure of the table is fixed, the MongoDB set does not have this constraint, and the document object that is stored in the collection can even embed the subdocument, or "child collections". They can eventually be described in a format similar to Bjson. We are here today to analyze the unique data management approach that MongoDB this feature brings. We still take Samus drive as an example to analyze, Samus Drive support two ways to access the database, the basic Way and LINQ way, the basic way in the previous article to introduce, LINQ way I do not want to explain the application instance alone, this article I will use two ways to compare the introduction.

One, the collection operations that contain subdocuments

There is such an application scenario, a website provides member login function, the user needs to register the account to be able to enjoy the member service, but the registrant may because the user data form entry item is too big to fill in, therefore the user information divides into the main information and the detailed information two items, the initial registration only needs to fill in the main material to be We intend to design the detailed information as a subdocument store.

1) LINQ Mode implementation

1. New data description class, describing user information

Copy Code code as follows:

<summary>
User main information
</summary>
public class UserInfo
{
public string UserId {get; set;}
public string UserName {get; set;}
public string PassWord {get; set;}
Public Detail 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. We want to create a new user business Operation class "USERBLL". This time to let the driver know the UserInfo class describes the field information for user data, and the Getmongo () method implements the configuration steps, Userbll complete code as follows:

Copy Code code as follows:

public class USERBLL
{
public string connectionString = "Mongodb://localhost";
public string databaseName = "MyDatabase";

Private Mongo Mongo;
Private Mongodatabase mongodatabase;

Note that the generic type is "UserInfo"
Private mongocollection<userinfo> mongocollection;

Public Userbll ()
{
MONGO = Getmongo ();
Mongodatabase = MONGO. Getdatabase (DatabaseName) as mongodatabase;
Mongocollection = mongodatabase.getcollection<userinfo> () as mongocollection<userinfo>;
Mongo. Connect ();
}
~USERBLL ()
{
Mongo. Disconnect ();
}

<summary>
Configure MONGO to map the class UserInfo to the collection
</summary>
Private Mongo Getmongo ()
{
var config = new Mongoconfigurationbuilder ();
Config. Mapping (Mapping =>
{
Mapping. DefaultProfile (Profile =>
{
Profile. Subclassesare (t => t.issubclassof (typeof (UserInfo)));
});
Mapping. Map<userinfo> ();
});
Config. ConnectionString (ConnectionString);
Return to new Mongo (config. Buildconfiguration ());
}
}

3. Then, define a Method "Insertsomedata ()" In the "Userbll" class to insert some data:

Copy Code code as follows:

<summary>
Insert some data
</summary>
public void Insertsomedata ()
{
UserInfo userInfo1 = new UserInfo ()
{
UserId = "1001",
UserName = "John",
PassWord = "123456"
};
Mongocollection.save (USERINFO1);

UserInfo UserInfo2 = new UserInfo ()
{
UserId = "1002",
UserName = "Dick",
PassWord = "123456",
Detail = new Detail ()
{
Address = "Hubei",
Age = 20,
Email = "Lisi@163.com"
}
};
Mongocollection.save (UserInfo2);

UserInfo UserInfo3 = new UserInfo ()
{
UserId = "1003",
UserName = "Harry",
PassWord = "123456",
Detail = new Detail ()
{
Address = "Guangdong",
Age = 20,
Email = "Wangwu@163.com"
}
};
Mongocollection.save (USERINFO3);

UserInfo UserInfo4 = new UserInfo ()
{
UserId = "1004",
UserName = "Zhao Liu",
PassWord = "123456",
Detail = new Detail ()
{
Address = "Hubei"
}
};
Mongocollection.save (USERINFO4);
}

4. Define a method to find the data "Select", which will look up user details, address in Hubei all users:

Copy Code code as follows:

<summary>
Query details address for the user information in Hubei
</summary>
Public list<userinfo> Select ()
{
Return Mongocollection.linq (). Where (x => x.detail.address = = "Hubei"). ToList ();
}

5. Also defines a method for deleting data that will remove all data from the collection:

Copy Code code as follows:

<summary>
Remove all user information
</summary>
public void DeleteAll ()
{
Mongocollection.remove (x => True);
}

6. Add the following code to the Main method:

Copy Code code as follows:

static void Main (string[] args)
{

USERBLL USERBLL = new USERBLL ();
Userbll.insertsomedata ();
var users = Userbll.select ();
foreach (var user in users)
{
Console.WriteLine (user. UserName + "is Hubei people");
};
Userbll.deleteall ();
}

7. The final implementation of the program, printing the following information:

Li Si is Hubei people
Zhao Liu is from Hubei province.

1) General implementation

Common way to implement do not want to speak, directly paste the code to see what the difference with the LINQ method:

Copy Code code as follows:

Class Program
{
static void Main (string[] args)
{
USERBLL USERBLL = new USERBLL ();
Userbll.insertsomedata ();
var users = Userbll.select ();
foreach (var user in users)
{
Console.WriteLine (user["UserName"). ToString () + "is Hubei people");
};
Userbll.deleteall ();

Console.ReadLine ();
}
}

public class USERBLL
{
public string connectionString = "Mongodb://localhost";
public string databaseName = "MyDatabase";
public string collectionname = "UserInfo";

Private Mongo Mongo;
Private Mongodatabase mongodatabase;
Private mongocollection<document> mongocollection;

Public Userbll ()
{
MONGO = new MONGO (connectionString);
Mongodatabase = MONGO. Getdatabase (DatabaseName) as mongodatabase;
Mongocollection = mongodatabase.getcollection<document> (collectionname) as mongocollection<document>;
Mongo. Connect ();
}
~USERBLL ()
{
Mongo. Disconnect ();
}

<summary>
Insert some data
</summary>
public void Insertsomedata ()
{
Document USERINFO1 = new document ();
userinfo1["UserId"] = "1001";
userinfo1["UserName"] = "John";
userinfo1["PassWord"] = "123456";
Mongocollection.save (USERINFO1);

Document UserInfo2 = new document ();
userinfo2["UserId"] = "1002";
userinfo2["UserName"] = "dick";
userinfo2["PassWord"] = "123456";
Subdocuments
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"] = "Harry";
userinfo3["PassWord"] = "123456";
var userinfo3detail = new Document ();
userinfo3detail["Address"] = "Guangdong";
Userinfo3detail["age"] = 20;
userinfo3detail["Email"] = "wangwu@163.com";
userinfo3["Detail"] = Userinfo3detail;
Mongocollection.save (USERINFO3);

Document USERINFO4 = new document ();
userinfo4["UserId"] = "1004";
userinfo4["UserName"] = "Zhao Liu";
userinfo4["PassWord"] = "123456";
var userinfo4detail = new Document ();
userinfo4detail["Address"] = "Hubei";
userinfo4["Detail"] = Userinfo4detail;
Mongocollection.save (USERINFO4);

}

<summary>
Query details address for the user information in Hubei
</summary>
Public ienumerable<document> Select ()
{
Return Mongocollection.find (new Document {{"detail.address", "Hubei"}}). Documents;
}

<summary>
Remove all user information
</summary>
public void DeleteAll ()
{
Mongocollection.remove (new Document {});
}
}

Finally, we output the Bjson format of all the user data information through this code:

Copy Code code as follows:

<summary>
Print Data Bjson
</summary>
public void Printbjson ()
{
String Bjson = String. Empty;
foreach (Var documet in Mongocollection.findall (). Documents)
{

Bjson + = Documet. ToString ();

}
Console.WriteLine (Bjson);
}

The results are as follows:

Copy Code code as follows:

{"UserId": "1001", "UserName": "John", "PassWord": "123456", "_id": "4d80ec1ab8a4731338000001"}
{"UserId": "1002", "UserName": "Dick", "PassWord": "123456", "Detail": {"Address": "Hubei", "Age": "," Email ":" Lisi@163.com "}," _id ":" 4d80ec1ab8a4731338000002 "}
{"UserId": "1003", "UserName": "Harry", "PassWord": "123456", "Detail": {"Address": "Guangdong", "Age": "," Email ":" Wangwu@163.c Om "}," _id ":" 4d80ec1ab8a4731338000003 "}
{"UserId": "1004", "UserName": "Zhao Liu", "PassWord": "123456", "Detail": {"Address": "Hubei"}, "_id": "4d80ec1ab8a473133800000 4 "}

Set operations containing "child collections"

Also for example: there is a school personnel management system to count the class and student information, now defines a "class set", the Student field in this collection is a "student collection", including all students in the class.

1) LINQ Mode implementation

Basic configuration I don't say much more, the data class is defined as follows:

Copy Code code 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;}
}

Inquire which class the student called "John" is in, and his details:

(This is actually in memory after ToList, LINQ direct query seems to drive does not support.) )

Copy Code code as follows:

Public list<classinfo> Select ()
{
Return Mongocollection.linq (). ToList (). Where (x => x.students.exists (s => s.name = = "John")). ToList ();
}

1) General implementation

Inquire which class the student called "John" is in, and his details:

Copy Code code as follows:

Public list<document> Select ()
{
var mongocollection = mongodatabase.getcollection ("ClassInfo");
Return mongocollection. Find (new Document {{"Students.name", "John"}}). Documents.tolist ();
}

Bjson to print data:

Copy Code code as follows:
{"_id": "4d814bae5c5f000000005f63", "ClassName": "1001", "Students": [{"Name": "John", "Age": ten}, {"name": "Dick", "age" : 0}]}
{"_id": "4d814bae5c5f000000005f64", "ClassName": "1002", "Students": []}
{"_id": "4d814bae5c5f000000005f65", "ClassName": "1003", "Students": [{"Name": "Harry", "Age": one}, {"Name": "Zhao Liu", "Age" : 9}]}

Third, summary

In this section, we find that MongoDB has its own unique document structure that describes some of the relationship characteristics between data objects. Although it does not have relational database table query as strong as the query, but also through the document structure to describe more flexible relationship characteristics, so to speak, relational database can do, MongoDB basically can do. Even some relational databases are not easy to do, MongoDB can be easily done, for example, describing the inheritance of data classes.

Author: Lee (Lipan)
Source: [Lipan] (http://www.cnblogs.com/lipan/)

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.