Embed or Reference?
You have now seen two ways to connect data in MongoDB.
You can embed data, which means you put it inside the document. Each order holds its items:
{
_id: 1,
customer: "Asha",
items: [
{ product: "pen", qty: 10 },
{ product: "notebook", qty: 2 }
]
}
Or you can reference data, which means you store a value that points to a document in another collection. Each movie stores its director's name, and the directors collection has the details:
movies:
{ _id: 1, title: "Inception",
director: "Christopher Nolan" }
directors:
{ _id: "Christopher Nolan", country: "UK" }
Choosing between these two is the main design decision in MongoDB.
Embed when the data belongs to one parent and you usually read it together with that parent. The items of an order belong to that order, and you show them with it. One query gets the whole order, with no join.
Reference when many documents share the same data. A director has many movies. If every movie kept its own copy of the director's country, you would have to update every one of those movies when the country changes. With a reference, the details are stored once. $lookup joins them when you need them.
Size matters too. One document can be at most 16 MB. The comments on a popular post can keep growing, so they usually go in their own collection, and each comment references its post.
A good rule to start with: embed by default. Reference when many documents share the data, or when it keeps growing.
Now answer one question about this choice.