Skip to main content

Command Palette

Search for a command to run...

When should we embed one document within another in MongoDB?

Updated
1 min read
When should we embed one document within
another in MongoDB?
R

Full Stack Developer with a passion for building web applications. PHP, Node.js, Laravel, MySQL, MongoDB. Love collaborating & making a difference

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

If you need to retrieve the address data with the name information frequently, then you need to issue multiple queries to resolve the references. In this case you can embed the address document in 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"
                }
              ]
 }

Sources:

Model One-to-Many Relationships With Embedded Documents — MongoDB Manual. www.mongodb.com/docs/manual/tutorial/model-embedded-one-to-many-relationships-between-documents.

More from this blog

R

Raja Muhammad Asher - Senior Software Engineer - Full Stack Developer

157 posts

Full Stack Developer with a passion for building web applications. PHP, Node.js, Laravel, ExpressJS, MySQL, MongoDB. Love collaborating & making a difference