In a relational database you normalize first and join later. In MongoDB the most important modeling question is different: should related data be embedded in one document, or stored in separate documents and referenced?
Embedding
Embedding puts related data inside the parent document:
db.customers.insertOne({
_id: 1,
name: "Ada Lovelace",
addresses: [
{ type: "home", city: "London", zip: "W1" },
{ type: "work", city: "London", zip: "EC1" }
]
});
Pros
- One read returns everything — no
$lookupneeded. - Single-document writes are atomic, so the customer and their addresses always change together.
Cons
- Documents have a 16 MB size limit.
- Arrays that grow without bound make documents larger and slower to update.
- Data embedded in many places must be updated in many places.
Referencing
Referencing stores related data in its own collection and keeps an ID:
db.orders.insertOne({
_id: 5001,
customerId: 1,
items: [{ sku: "DB-101", : }],
: ()
});
db..({ : , : - });
