SyntaxStudy
Sign Up
MongoDB Embedded Documents vs References
MongoDB Beginner 1 min read

Embedded Documents vs References

One of the most important design decisions in MongoDB is choosing between embedding related data inside a document versus storing a reference (an ObjectId) to another collection. Embedding works well when the related data is always accessed together, has a bounded size, and is owned by the parent document — for example, storing an array of order line items inside an order document. References make more sense when the related entity is shared across many parents, can grow unboundedly, or needs to be queried independently — for example, a user referenced by thousands of orders. The general MongoDB guidance is to embed for "has-a" relationships and reference for "belongs-to-many" relationships, but real-world decisions depend heavily on your read and write patterns.
Example
// EMBEDDED approach — address lives inside the user document
db.users.insertOne({
  _id: ObjectId(),
  name: "Bob",
  // Address is always fetched with the user, fits well embedded
  address: {
    street: "123 Main St",
    city: "Austin",
    state: "TX",
    zip: "78701"
  }
})

// REFERENCE approach — posts reference the author by ObjectId
db.authors.insertOne({ _id: ObjectId("aaa111"), name: "Alice" })

db.posts.insertOne({
  _id: ObjectId(),
  title: "MongoDB Design Patterns",
  // Only store the reference; use $lookup to join when needed
  authorId: ObjectId("aaa111"),
  body: "..."
})

// Fetch post with author using $lookup (see aggregation topic)
db.posts.aggregate([
  { $lookup: {
      from: "authors",
      localField: "authorId",
      foreignField: "_id",
      as: "author"
  }},
  { $unwind: "$author" }
])