Problem Statement
What are embedded documents in MongoDB and when should you use them?
Explanation
Embedded documents are documents nested inside another document. Instead of splitting related data across multiple collections and using references, you store the related data directly within the parent document.
Use embedded documents when you have a one-to-one or one-to-few relationship, when the embedded data is always accessed together with the parent document, and when the embedded data does not need to be queried independently.
For example, storing a user's address inside the user document makes sense because the address belongs to that user and is usually retrieved together. Embedding improves read performance because you get all related data in a single query without joins.
Code Solution
SolutionRead Only
// Embedded document example
{
_id: 1,
name: "John Doe",
email: "john@example.com",
address: {
street: "123 Main St",
city: "New York",
zip: "10001",
country: "USA"
},
phones: [
{ type: "home", number: "555-1234" },
{ type: "work", number: "555-5678" }
]
}