Database Reference
In-Depth Information
In the nonrelational approach, the document might look something like the following:
{
"Type": "CD",
"Artist": "Nirvana",
"Title": "Nevermind",
"Genre": "Grunge",
"Releasedate": "1991.09.24",
"Tracklist": [
{
"Track" : "1",
"Title" : "Smells Like Teen Spirit",
"Length" : "5:02"
},
{
"Track" : "2",
"Title" : "In Bloom",
"Length" : "4:15"
}
]
}
In this example, the track list information is embedded in the document itself. This
approach is both incredibly efficient and well organized. All the information that you
wish to store regarding this CD is added to a single document. In the relational version
of the CD database, this requires at least two tables; in the nonrelational database, it
requires only one collection and one document.
When information is retrieved for a given CD, that information only needs to be
loaded from one document into RAM, not from multiple documents. Remember that
every reference requires another query in the database.
the rule of thumb when using MongoDB is to embed data whenever you can.
this approach is far more efficient and almost always viable.
Tip
At this point, you might be wondering about the use case in which an application has
multiple users. Generally speaking, a relational database version of the aforementioned
CD app would require that you have one table that contains all your users and two tables
for the items added. For a nonrelational database, it would be good practice to have
separate collections for the users and the items added. For these kinds of problems,
MongoDB allows you to create references in two ways: manually or automatically. In
the latter case, you use the DBRef specification, which provides more flexibility in case a
collection changes from one document to the next. You will learn more about these two
approaches in Chapter 4.
 
 
Search WWH ::




Custom Search