Schema Design: Embedding vs Referencing
The single biggest modeling decision in MongoDB: should related data live inside the same document (embedding), or in a separate collection linked by an id (referencing)?
Embedding: keep related data together
A blog post and its handful of comments are read together almost every time the post is viewed, so embedding the comments directly inside the post document avoids a second query entirely:
{
_id: ObjectId("..."),
title: "Hello, MongoDB!",
comments: [
{ author: "Sam", text: "Great post!" },
{ author: "Noah", text: "Thanks for this." }
]
}
One findOne() call returns the post and every comment on it — no join, no second round trip.
Referencing: keep related data separate
A user and every order they've ever placed is a different story — there could be thousands of orders, they're usually queried independently of the user record, and you rarely need "the user and all their orders" in one shot:
// users collection
{ _id: ObjectId("u1"), name: "Priya" }
// orders collection
{ _id: ObjectId("o1"), userId: ObjectId("u1"), total: 42.50 }
{ _id: ObjectId("o2"), userId: ObjectId("u1"), total: 18.00 }
Each order stores a userId pointing back to the user — the same idea as a foreign key in a SQL table. Fetching a user's orders is a separate query: db.orders.find({ userId: ObjectId("u1") }).
Choosing between them
Embed when the related data is bounded, usually small, and almost always read together with its parent. Reference when the related data can grow without bound, is queried on its own, or is shared across multiple parent documents.