Database Reference
In-Depth Information
appendix B
Design patterns
B.1
Patterns
The early chapters of this topic implicitly advocate a certain set of design patterns.
Here I'll summarize those patterns and augment them with a few patterns that fall
outside the flow of the text.
B.1.1
Embed versus reference
Suppose you're building a simple application in MongoDB that stores blog posts and
comments. How do you represent this data? Do you embed the comments in their
respective blog post documents? Or is it better to create two collections, one for posts
and the other for comments, and then relate the comments to the posts with an object
id reference?
This is the problem of embedding versus referencing, and it's a common source
of confusion for new users of MongoDB. Fortunately, there's a simple rule of thumb
that works for most schema design scenarios: Embed when the child objects always
appear in the context of their parent. Otherwise, store the child objects in a separate
collection.
What does this mean for blog posts and comments? It depends on the application.
If the comments always appear within a blog post, and if they don't need to be
ordered in arbitrary ways (by post date, comment rank, and so on), then embedding is
fine. But if, say, you want to be able to display the most recent comments, regardless of
which post they appear on, then you'll want to reference. Embedding may provide a
slight performance advantage, but referencing is far more flexible.
B.1.2
One-to-many
As stated in the previous section, you can represent a one-to-many relationship by
either embedding or referencing. You should embed when the many object intrinsi-
cally belongs with its parent and rarely changes. The schema for a how-to applica-
tion illustrates this well. The steps in each guide can be represented as an array of
sub-documents because these steps are an intrinsic part of the guide, and rarely
change:
{ title: "How to soft-boil an egg",
steps: [
249
Search WWH ::




Custom Search