MongoDB Academy · บทเรียน

การอ้างอิง: ความสัมพันธ์หนึ่งต่อหลายรายการและหลายต่อหลายรายการ

ผู้เรียนจะจัดเก็บการอ้างอิง ObjectId ข้ามคอลเลกชัน และใช้ $lookup เพื่อเชื่อมโยงข้อมูลขณะคิวรี

บทเรียน 2 จาก 413 ขั้นตอน

การอ้างอิง: ความสัมพันธ์หนึ่งต่อหลายรายการและหลายต่อหลายรายการ เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What Is Referencing?

Referencing means storing an ObjectId (or another unique identifier) inside one document that points to a document in a different collection, similar to a foreign key in relational databases. Instead of nesting data, you link it. This approach is essential when the child count is large, when children are shared among multiple parents, or when children need to be queried independently.

One-to-Many With References

In a one-to-many relationship a single parent has many children. A user can have hundreds of orders—far too many to safely embed. Instead, each order document stores a userId reference pointing back to the parent user. This keeps the user document small while allowing unbounded order growth.

// users collection
db.users.insertOne({ _id: ObjectId('u1'), name: 'Alice', email: 'alice@example.com' });

// orders collection — each order references the user
db.orders.insertMany([
  { _id: ObjectId('o1'), userId: ObjectId('u1'), total: 49.99, status: 'shipped' },
  { _id: ObjectId('o2'), userId: ObjectId('u1'), total: 120.00, status: 'pending' }
]);

Many-to-Many With References

A many-to-many relationship—like students enrolled in multiple courses, and courses containing multiple students—cannot be embedded without duplication. The cleanest approach is to store an array of references on one side. For example, each student document holds an array of courseId values it is enrolled in.

db.students.insertOne({
  _id: ObjectId('s1'),
  name: 'Bob',
  enrolledCourses: [ ObjectId('c1'), ObjectId('c2'), ObjectId('c3') ]
});

db.courses.insertOne({
  _id: ObjectId('c1'),
  title: 'MongoDB Fundamentals',
  instructorId: ObjectId('i1')
});

Joining References With $lookup

To retrieve a document along with its referenced data, use the $lookup aggregation stage. It performs a left outer join between two collections. The from field names the collection to join, localField is the reference field in the current collection, and foreignField is the field to match in the joined collection.

// Fetch orders and join the user for each order
db.orders.aggregate([
  { $match: { status: 'shipped' } },
  {
    $lookup: {
      from: 'users',
      localField: 'userId',
      foreignField: '_id',
      as: 'user'
    }
  },
  { $unwind: '$user' },
  { $project: { total: 1, status: 1, 'user.name': 1 } }
]);

Child-Side vs Parent-Side References

You can store the reference on either side of the relationship. Child-side reference: the child stores the parent's ID (e.g., order.userId)—queries like 'all orders for a user' are simple range queries. Parent-side reference: the parent stores an array of child IDs (e.g., user.orderIds)—useful when you frequently retrieve all child IDs without querying child documents.

Many-to-Many $lookup Example

To resolve a many-to-many relationship—finding all courses a student is enrolled in—use $lookup with the array of IDs stored in the student document. The $in syntax inside $lookup's pipeline form lets you match multiple IDs efficiently.

db.students.aggregate([
  { $match: { name: 'Bob' } },
  {
    $lookup: {
      from: 'courses',
      localField: 'enrolledCourses',
      foreignField: '_id',
      as: 'courses'
    }
  },
  { $project: { name: 1, 'courses.title': 1 } }
]);

Referencing in Mongoose With populate()

Mongoose provides the populate() method as an abstraction over $lookup. You declare a field as a reference using type: mongoose.Schema.Types.ObjectId, ref: 'ModelName', and then call .populate('fieldName') on a query to automatically resolve the reference to the full document.

const orderSchema = new mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  total: Number,
  status: String
});

// Usage: populate resolves userId to the full User document
const orders = await Order.find({ status: 'shipped' }).populate('userId', 'name email');

Indexing the Reference Field

When querying child documents by their parent reference—such as all orders for a given user—MongoDB must scan the entire collection unless the userId field is indexed. Always create an index on reference fields used in frequent queries. An index on userId turns a full collection scan into a fast index scan.

// Create an index on the reference field for fast lookups
db.orders.createIndex({ userId: 1 });

// Now this query hits the index instead of scanning all orders
db.orders.find({ userId: ObjectId('u1') });

Shared Data: The Case for References

When multiple documents share the same child—like many blog posts sharing the same author profile—embedding would duplicate the author data in every post. With referencing, only the authorId is stored in each post. If the author's name changes, one update to the authors collection propagates everywhere, whereas with embedding you'd have to update every post.

Performance Trade-offs of References

Referencing requires at least two round trips to the database (or one aggregation with $lookup) to fetch the parent and its children. This is slower than a single embedded read, but the trade-off is often worth it when children are large in number, updated independently, or shared across parents. Design choices always depend on your dominant query patterns.

Combining Embedding and Referencing

Real schemas often mix both strategies. An order document might embed the shipping address (immutable at order time) while referencing the productId for each line item (shared catalogue data). This hybrid approach co-locates data that changes together and references data that is shared or grows independently. There is no rule against mixing the two patterns in a single document.

db.orders.insertOne({
  _id: ObjectId(),
  userId: ObjectId('u1'),           // reference to user
  shippingAddress: {                // embedded snapshot
    street: '123 Maple St',
    city: 'Austin',
    zip: '78701'
  },
  items: [
    { productId: ObjectId('p1'), qty: 2, price: 19.99 }  // reference to product
  ]
});

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: referencing stores ObjectId links across collections, $lookup and populate() resolve references at query time, and referencing is preferred when child count is large, data is shared, or children need independent updates. Next up we explore the unbounded array anti-pattern—when embedding goes wrong.

เริ่มต้นได้ฟรี

เรียนรู้ JavaScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
30
บทเรียน
120

คำถามที่พบบ่อย

บทเรียน “การอ้างอิง: ความสัมพันธ์หนึ่งต่อหลายรายการและหลายต่อหลายรายการ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การอ้างอิง: ความสัมพันธ์หนึ่งต่อหลายรายการและหลายต่อหลายรายการ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การอ้างอิง: ความสัมพันธ์หนึ่งต่อหลายรายการและหลายต่อหลายรายการ”

ผู้เรียนจะจัดเก็บการอ้างอิง ObjectId ข้ามคอลเลกชัน และใช้ $lookup เพื่อเชื่อมโยงข้อมูลขณะคิวรี คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การอ้างอิง: ความสัมพันธ์หนึ่งต่อหลายรายการและหลายต่อหลายรายการ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม

ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การฝังข้อมูล: ความสัมพันธ์หนึ่งต่อไม่กี่รายการ
  2. การอ้างอิง: ความสัมพันธ์หนึ่งต่อหลายรายการและหลายต่อหลายรายการ
  3. รูปแบบต่อต้านอาร์เรย์ไร้ขอบเขต
  4. กรอบการตัดสินใจออกแบบสคีมา
← กลับไปที่ MongoDB Academy