MongoDB Schema Design: Embedding vs Referencing
MongoDB schema design is about shaping documents around how your application reads data. The golden rule: data that is accessed together should be stored together. The two main tools are embedding and referencing.
Embedding
Put related data inside the parent document. One read returns everything, and updates to the whole document are atomic.
db.orders.insertOne({
orderNo: 102,
customer: { name: "Sara Khan", city: "Karachi" },
items: [
{ product: "Green Tea", qty: 25, price: 6 }
],
orderDate: ISODate("2026-01-09")
}){ acknowledged: true, insertedId: ObjectId('6720a9...') }Referencing
Store the _id of another document instead, like a foreign key. Use it when related data is large, shared by many parents, or grows without limit.
const cust = db.customers.findOne({ name: "Alpha Traders" })
db.orders.insertOne({ orderNo: 101, customerId: cust._id, total: 125 }){ acknowledged: true, insertedId: ObjectId('6720a9...') }Choosing Between Them
- One-to-few (addresses of a user): embed
- One-to-many (orders of a customer): reference from the child, or embed a summary
- One-to-huge (log lines of a server): always reference
- Data read together and rarely changed independently: embed
- Never let an array grow without bound — remember the 16 MB limit
Schema Validation
Flexible does not mean unvalidated. A $jsonSchema validator rejects documents that break your rules.
db.createCollection("users", {
validator: { $jsonSchema: {
bsonType: "object",
required: ["email"],
properties: { email: { bsonType: "string", pattern: "@" } }
} }
})
db.users.insertOne({ name: "No email" }){ ok: 1 }
MongoServerError: Document failed validationFrequently asked questions
Should I embed or reference in MongoDB?
Embed when the data is read together and bounded in size. Reference when the related data is large, shared, or unbounded. Many real schemas mix both.
Does MongoDB support joins?
Yes, the $lookup aggregation stage joins collections. Frequent joins can be a sign that embedding would serve you better.
Is denormalisation bad in MongoDB?
No. Duplicating some data (such as a customer name on each order) is a normal trade-off for faster reads, as long as you plan how to update it.