Model One-to-One Relationships with Embedded Documents
Overview
This page describes a data model that uses embedded documents to describe a one-to-onerelationship between connected data.
Pattern
Consider the following example that maps patron and addressrelationships. The example illustrates the advantage of embedding overreferencing if you need to view one data entity in context of theother. In this one-to-one relationship between patron
andaddress
data, the address
belongs to the patron
.
In the normalized data model, the address
document contains areference to the patron
document.
- {
- _id: "joe",
- name: "Joe Bookreader"
- }
- {
- patron_id: "joe",
- street: "123 Fake Street",
- city: "Faketon",
- state: "MA",
- zip: "12345"
- }
If the address
data is frequently retrieved with the name
information, then with referencing, your application needs to issuemultiple queries to resolve the reference. The better data model wouldbe to embed the address
data in the patron
data, as in thefollowing document:
- {
- _id: "joe",
- name: "Joe Bookreader",
- address: {
- street: "123 Fake Street",
- city: "Faketon",
- state: "MA",
- zip: "12345"
- }
- }
With the embedded data model, your application can retrieve thecomplete patron information with one query.