Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

Model One-to-Many Relationships with Embedded Documents

On this page

  • Example
  • Embedded Document Pattern
  • Learn More

Create a data model that uses embedded documents to describe a one-to-many relationship between connected data. Embedding connected data in a single document can reduce the number of read operations required to obtain data. In general, structure your schema so your application receives all of its required information in a single read operation. For example, you can use the the embedded one-to-many model to describe the following relationships:

  • Country to major cities

  • Author to books

  • Student to classes

The example schema contains three entities, with address one and address two belonging to the same patron:

// patron document
{
_id: "joe",
name: "Joe Bookreader"
}
// address one
{
street: "123 Fake Street",
city: "Faketon",
state: "MA",
zip: "12345"
}
// address two
{
street: "1 Some Other Street",
city: "Boston",
state: "MA",
zip: "12345"
}

In this example the application needs to display information for the patron and both address objects on a single page. To allow your application to retreive all necessary information with a single query, embed the address one and address two information inside of the patron document:

{
"_id": "joe",
"name": "Joe Bookreader",
"addresses": [
{
"street": "123 Fake Street",
"city": "Faketon",
"state": "MA",
"zip": "12345"
},
{
"street": "1 Some Other Street",
"city": "Boston",
"state": "MA",
"zip": "12345"
}
]
}
←  Model One-to-One Relationships with Embedded DocumentsModel One-to-Many Relationships with Document References →