Database Reference
In-Depth Information
In our example phone book application, we might store Jenny's contact information in a doc-
ument as follows:
{
"_id" : 3 ,
"name" : "Jenny" ,
"zip_code" : "01209" ,
"numbers" : [ "555-333-3456" , "555-334-3411" ]
}
As you can see, we're now able to store contact information in the initial Table 1-2 format
without going through the process of normalization. Alternatively, we could “normalize” our
model to remove the array, referencing the contact document by its _id field:
// Contact document:
{
"_id" : 3 ,
"name" : "Jenny" ,
"zip_code" : "01209"
}
// Number documents:
{ "contact_id" : 3 , "number" : "555-333-3456" }
{ "contact_id" : 3 , "number" : "555-334-3411" }
The remainder of this chapter is devoted to helping you decide whether referencing or embed-
ding is the correct solution in various contexts.
Embedding for Locality
One reason you might want to embed your one-to-many relationships is data locality. As dis-
cussed earlier, spinning disks are very good at sequential data transfer and very bad at random
seeking. And since MongoDB stores documents contiguously on disk, putting all the data you
need into one document means that you're never more than one seek away from everything
you need.
MongoDB also has a limitation (driven by the desire for easy database partitioning) that there
are no JOIN operations available. For instance, if you used referencing in the phone book ap-
plication, your application might do something like the following:
Search WWH ::




Custom Search