Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 70 ยท Schema design

Modeling Relationships

Model one-to-many and many-to-many links, trees with parent references and materialized paths, and graph-like data in MongoDB, including $graphLookup.

Real data is full of relationships: an author has books, a book has many authors, a category has subcategories, a person follows other people. A relational database answers all of these with foreign keys and join tables. MongoDB gives you more choices, because a relationship can live inside a document (embedding), or be stored as a reference to another document's _id. You already met the trade-off in Embedding vs Referencing; this lesson applies it to the relationship shapes you will meet most often.

We will go through one-to-many, many-to-many, trees and graph-like data. The first three runnable examples use plain JavaScript stand-ins (see The Practice Engine Used in This Tutorial). The $graphLookup stage is shown as a real mongosh command, followed by a stand-in that walks the same data.

Four relationship shapes

One-to-many Embed few, reference many.
Many-to-many Arrays of ids on one or both sides.
Trees Parent, children or a path string.
Graphs Walk links with $graphLookup.

The right shape depends on how you read the data.

1 / 2

One-to-many

The first question is how many "many" is.

  • One-to-few (a user and their two or three addresses): embed the children in the parent as an array. One read returns everything.
  • One-to-many (a blog post and its hundreds of comments): either embed a small recent subset and reference the rest, or store the children in their own collection.
  • One-to-squillions (a server and its millions of log lines): never put the children in an array. Each child stores a reference to its parent, for example { host: "web-1", msg: "..." }.

The rule of thumb: put the reference on the side that cannot grow without bound. A document with an ever-growing array hits the 16 MB document limit and becomes slow to rewrite. A child that stores one parent id is always small, and db.reviews.find({ bookId: "b1" }) with an index on bookId is a cheap query.

JavaScript
// real mongosh: reviews live in their own collection and point at the book
db.reviews.createIndex({ bookId: 1 })
db.reviews.find({ bookId: "b1" }).sort({ stars: -1 }).limit(5)

Many-to-many

Books have several authors and authors write several books. In SQL you would create a join table. In MongoDB the usual answer is an array of references on one side:

JavaScript
{ _id: "a1", name: "Ines", bookIds: ["b1", "b2"] }

Because arrays are indexable (a multikey index, see Index Types), db.authors.find({ bookIds: "b2" }) finds every author of book b2 quickly. Pick the side that is smaller and more stable to hold the array. If you must query both directions all the time, store the ids on both sides, but remember that every change is now two writes, and they are not atomic across documents unless you use a transaction.

The next TryIt builds both relationships on a tiny library and answers three questions.

JS One-to-many and many-to-many with references

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The "join" in the first loop is done by the application with a second lookup. MongoDB can also do it for you with $lookup (Joining with $lookup), at a cost.

Trees

Categories, org charts, comment threads and file systems are trees. MongoDB has four classic ways to store one, and each makes different questions cheap:

Pattern What a node stores Cheap Expensive
Parent reference parent: "computers" children of a node, move a subtree whole subtree, ancestors
Child references children: ["laptops", "tablets"] children, descendants by walking finding the parent
Array of ancestors ancestors: ["electronics", "computers"] ancestors, whole subtree, one index moving a subtree
Materialized path path: ",electronics,computers," subtree with an anchored regex moving a subtree

Parent references are the simplest and the best default when the tree changes. A materialized path stores the route from the root as a string, so the whole subtree of computers is { path: /^,electronics,computers,/ }. An anchored regex can use an index (see Text Matching and Regular Expressions). Moving a node means rewriting the path of every descendant, so choose paths for trees that are read far more than they are reorganized.

Graph-like data and $graphLookup

When you do not know how deep to walk, for example "everyone reporting up to this manager, at any level" or "all categories under Electronics", use the aggregation stage $graphLookup. It starts from a document, follows a field to matching documents, then repeats from those, recording the depth. This is the real shell form:

JavaScript
db.categories.aggregate([
  { $match: { _id: "electronics" } },
  { $graphLookup: {
      from: "categories",
      startWith: "$_id",
      connectFromField: "_id",
      connectToField: "parent",
      as: "descendants",
      depthField: "level"
  } }
])

Reading it: begin with the value of _id, find categories whose parent equals it, then from each found _id find the next batch, and so on until nothing new turns up. The results land in the descendants array, each carrying a level number (starting at 0). Add maxDepth to limit the walk. Without an index on the connectToField (parent here), every hop scans the collection, so index it. The stand-in below stores a small category tree both ways and answers the same questions with a parent walk, a path prefix test and a breadth-first walk that mimics $graphLookup.

JS Tree queries: parent, path and a graph walk

Press Run (or Ctrl + Enter) to see the console output here.

No output.

All three approaches return the same set. What differs is the cost: the path version needs one indexed query, the parent version needs one query per level, and $graphLookup does the per-level work inside the server.

Manual references and DBRef

When a document points at another one, you can store that pointer in two ways.

A manual reference stores just the _id of the target, and your application knows which collection it belongs to:

JavaScript
{ _id: 101, title: "Intro to MongoDB", authorId: ObjectId("66a1f0c2e4b0a1b2c3d4e5f6") }

This is what $lookup and almost all real schemas use. It is small, fast, and every query tool understands it. The weakness is that the document says nothing about where the id points, so the code (or a convention such as the field name authorId) has to know.

A DBRef is a small, standardized document that carries that information with the reference:

JavaScript
{
  _id: 101,
  title: "Intro to MongoDB",
  author: { $ref: "authors", $id: ObjectId("66a1f0c2e4b0a1b2c3d4e5f6") }
  // optionally: $db: "publishing" for a collection in another database
}

$ref is the collection name, $id is the _id of the target, and $db is an optional database name. The field order matters ($ref, then $id, then $db), and the names are fixed.

What a DBRef does not do is important: the server never follows it. A query for the book returns the { $ref, $id } document, and your code (or a driver helper or an ODM such as Mongoose) must then run a second query on authors. $lookup does not understand a DBRef as a join key either, although you can reach the pieces with localField: "author.$id". MongoDB's own guidance is to use manual references unless you have a specific reason.

DBRef earns its place in one situation: a field that can point to different collections, where the document must say which one. A comment might attach to a posts, a photos or a videos document, and a DBRef-style { $ref, $id } lets one generic resolver handle all three. A manual alternative is a pair of fields, { targetType: "photos", targetId: 55 }, which is just as clear and works better with indexes and $lookup.

Manual reference DBRef
Stores Just the _id { $ref, $id, $db? }
Size Smallest Larger (collection name repeated in every document)
Knows its target collection No, the schema or code does Yes, each reference says so
Followed by the server No (use $lookup) No (resolved by the application)
Typical use Nearly everything Polymorphic links, tools that expect the convention

Either way, a reference is not a foreign key. MongoDB does not check that the target exists and does not prevent deleting it, so the application has to handle dangling references (see Embedding vs Referencing for when to avoid references altogether). The model below resolves both kinds, and shows a dangling reference.

JS Resolving a manual reference and a DBRef

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both approaches return null for a missing target, which is why code that follows references must check for it. In a hot path, embedding or copying the few fields you display (such as the author's name) avoids the second query entirely.

Choosing quickly

Start from the question you ask most often. If it is "show me this thing and its related items", embed or store an array of ids. If the related side is large or unbounded, put the reference on the child. For hierarchies, begin with parent references and add a path or ancestors array only when subtree queries become common. For arbitrary-depth walking over relationships that are not strictly a tree, use $graphLookup, and consider a dedicated graph database if graph traversal is your main workload.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A server produces millions of log lines. Where should the relationship be stored?

    Unbounded arrays hit the 16 MB limit and make updates slow. A child that stores its parent id stays small and can be indexed.
  2. 2. Which tree pattern makes 'the whole subtree of a node' one anchored-regex query?

    A path string such as ',electronics,computers,' lets an anchored prefix pattern select every descendant in a single query, and an index can serve it.
  3. 3. What does connectToField mean in $graphLookup?

    Each hop takes values from connectFromField and finds documents in 'from' whose connectToField equals them. as names the output array and maxDepth limits the hops.
  4. 4. Why index the connectToField used by $graphLookup?

    The stage still works without an index, but each hop becomes a collection scan, which gets slow on large collections.

Summary

  • Decide by size and growth: embed for few, reference for many, and put the reference on the side that cannot grow without bound.
  • Many-to-many is usually an array of ids on one side, queried through a multikey index; storing ids on both sides speeds up reads but doubles the writes.
  • Trees: parent references are the flexible default; ancestors arrays and materialized paths make subtree queries cheap but moves expensive.
  • $graphLookup walks relationships to any depth using connectFromField, connectToField, as, and optionally depthField and maxDepth; index the connect-to field.
  • The TryIts here are JavaScript stand-ins; the mongosh blocks are real MongoDB.

Next, learn how to keep your documents in shape with Schema Validation.