Tutorials Logic, IN info@tutorialslogic.com

MongoDB Relationships One to Many $lookup

Modelling Relationships in MongoDB

MongoDB supports two primary strategies for representing relationships: embedding (denormalization) and referencing (normalization). Unlike SQL, there are no foreign key constraints - you manage relationships in application logic or through the aggregation pipeline.

Embedded Documents

One-to-One and One-to-Many Embedded

One-to-One and One-to-Many Embedded
// ONE-TO-ONE EMBEDDED: User with address
{
  "_id": ObjectId("u1"),
  "name": "Alice Johnson",
  "address": { "street": "123 Main St", "city": "New York", "zip": "10001" }
}

// ONE-TO-MANY EMBEDDED: Post with comments (bounded array)
{
  "_id": ObjectId("p1"),
  "title": "Getting Started with MongoDB",
  "comments": [
    { "user": "Bob",   "text": "Great article!", "date": ISODate("2024-01-10") },
    { "user": "Carol", "text": "Very helpful.",   "date": ISODate("2024-01-11") }
  ]
}

// Query embedded field
db.posts.find({ "comments.user": "Bob" })

// Update embedded array element using positional operator
db.posts.updateOne(
  { _id: ObjectId("p1"), "comments.user": "Bob" },
  { $set: { "comments.$.text": "Updated comment!" } }
)

Choose Embedding Or Referencing

MongoDB stores documents rather than enforcing foreign keys between tables. Model data around application reads and updates. Embed a child document when it belongs to one parent, is read with that parent, remains bounded in size, and can be updated atomically with the parent. Addresses or a small set of order line snapshots often fit this pattern.

Use references when related data is shared, grows without a practical bound, changes independently, or needs separate access control and lifecycle. Store the referenced _id and load the related document in another query or through an aggregation. MongoDB does not automatically guarantee that the referenced document exists.

One-to-many relationships require special attention to growth. Embedding millions of comments or followers in one document exceeds practical document and update limits. Store unbounded children in their own collection with the parent ID indexed, then paginate them. Keep duplicated display fields only when there is a clear synchronization plan.

  • Embed bounded data owned by one aggregate.
  • Reference shared or independently changing data.
  • Keep unbounded child collections separate.
  • Index every common relationship lookup.
  • Document how duplicated fields stay synchronized.

Manual References

One-to-Many Referenced with $lookup

One-to-Many Referenced with $lookup
// users collection
{ "_id": ObjectId("u1"), "name": "Alice Johnson", "email": "alice@example.com" }

// orders collection - each order references the user
{ "_id": ObjectId("o1"), "userId": ObjectId("u1"), "total": 1299.99, "status": "shipped" }
{ "_id": ObjectId("o2"), "userId": ObjectId("u1"), "total": 45.00,   "status": "pending" }

// Join using $lookup aggregation
db.users.aggregate([
  { $match: { _id: ObjectId("u1") } },
  { $lookup: {
      from: "orders",
      localField: "_id",
      foreignField: "userId",
      as: "orders"
  }},
  { $project: { name: 1, email: 1, orderCount: { $size: "$orders" }, orders: 1 } }
])

Many-to-Many Relationships

Many-to-Many with Arrays of References

Many-to-Many with Arrays of References
// Students and Courses - many-to-many
// students collection
{
  "_id": ObjectId("s1"),
  "name": "Bob Smith",
  "enrolledCourses": [ObjectId("c1"), ObjectId("c2")]
}

// courses collection
{
  "_id": ObjectId("c1"),
  "title": "MongoDB Fundamentals",
  "enrolledStudents": [ObjectId("s1"), ObjectId("s2")]
}

// Find all courses a student is enrolled in
db.courses.find({ _id: { $in: [ObjectId("c1"), ObjectId("c2")] } })

// Add a student to a course
db.courses.updateOne(
  { _id: ObjectId("c1") },
  { $addToSet: { enrolledStudents: ObjectId("s3") } }
)
db.students.updateOne(
  { _id: ObjectId("s3") },
  { $addToSet: { enrolledCourses: ObjectId("c1") } }
)

Embed vs Reference Decision Guide

Embed vs Reference Decision Guide
// EMBED when:
// - Data is always accessed together with the parent
// - The sub-document is small and bounded (e.g., max 10-20 items)
// - The sub-document is not shared across multiple parents
// - You want atomic reads/writes in a single operation

// REFERENCE when:
// - Data is accessed independently of the parent
// - The array could grow unboundedly (e.g., all comments on a viral post)
// - The same data is referenced by multiple documents
// - The sub-document is large and rarely needed

// Example: User profile - EMBED (always needed together)
{ "_id": ObjectId("u1"), "name": "Alice", "profile": { "bio": "...", "avatar": "..." } }

// Example: User orders - REFERENCE (many orders, accessed separately)
// orders: { userId: ObjectId("u1"), total: 99.99, ... }
// db.orders.find({ userId: ObjectId("u1") })

Aggregation, Transactions, Consistency, And Sharding

$lookup performs server-side joins in aggregation pipelines, but large unindexed joins can consume substantial memory and time. Filter and project early, index local and foreign keys, and inspect explain output. Sometimes two focused application queries are simpler and faster than one broad aggregation.

Single-document updates are atomic. Multi-document transactions are available when an invariant spans documents, but they add latency and operational constraints. Prefer aggregate boundaries that keep common invariants in one document, and use transactions only when the business rule genuinely requires them.

In sharded clusters, relationship access should align with shard keys when possible. Cross-shard lookup and transactions are more expensive. Plan cardinality, distribution, and routing before scale. Reconciliation jobs can detect missing references or stale denormalized fields because schema flexibility does not remove data-quality responsibility.

  • Filter before $lookup and project only needed fields.
  • Use transactions only for true multi-document invariants.
  • Align shard keys with relationship access patterns.
  • Monitor document growth and join execution.
  • Reconcile references and denormalized copies periodically.

Referenced posts and authors with $lookup

Filter posts first, then join only the required author fields.

Referenced posts and authors with $lookup
db.posts.aggregate([
  { $match: { status: \"published\" } },
  { $sort: { publishedAt: -1 } },
  { $limit: 20 },
  { $lookup: {
      from: \"users\",
      localField: \"authorId\",
      foreignField: \"_id\",
      as: \"author\"
  } },
  { $unwind: \"$author\" },
  { $project: { title: 1, publishedAt: 1, \"author.name\": 1 } }
]);
  • Index posts.status and publishedAt for the initial query.
  • The users _id index supports the join.
  • Handle deleted or missing authors deliberately.

Bounded embedded order lines

Snapshot product details needed to preserve order history.

Bounded embedded order lines
db.orders.insertOne({
  customerId: ObjectId(\"64f000000000000000000001\"),
  status: \"pending\",
  lines: [
    {
      productId: ObjectId(\"64f000000000000000000010\"),
      name: \"Keyboard\",
      quantity: 2,
      unitPrice: NumberDecimal(\"49.90\")
    }
  ],
  createdAt: new Date()
});
  • Order line snapshots should not change with the product catalog.
  • Keep the line count bounded.
  • Use decimal values for currency.
Before you move on

MongoDB Relationships One to Many $lookup Mastery Check

4 checks
  • Choose embedding or references from cardinality, update frequency, read shape, and atomicity requirements.
  • Prevent unbounded embedded arrays and document how relationship records are deleted or archived.
  • Index the local and foreign fields used by relationship queries and inspect the resulting plan.
  • Version relationship changes so older documents remain readable during a migration.

MongoDB Questions Learners Ask

Yes, when the child set is owned and remains reasonably bounded.

Documents grow, updates become costly, and the 16 MB document limit can be reached.

No. It can join collections, but frequent joins may signal that the document model does not match reads.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.