← Back to MongoDB Course | Chapter 9: Schema Design | Lesson 2 of 7

One-to-one/one-to-many/many-to-many

Relationships are modelled by embedding or by storing ids, depending on how many items are involved.

One-to-one/one-to-many/many-to-many

One-to-one: embed. One-to-few: embed an array. One-to-many: reference from the many side or embed if bounded. One-to-squillions: store the parent id in each child. Many-to-many: arrays of ids on one or both sides, or a linking collection.

Note: For one-to-many with large counts, keep the parent id in the child documents.

Example: One-to-one/one-to-many/many-to-many

bash
test> db.students.insertMany([{ _id: 1, name: "Ada", courseIds: [10, 11] }, { _id: 2, name: "Bob", courseIds: [11] }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
test> db.courses.insertMany([{ _id: 10, title: "Math" }, { _id: 11, title: "Code" }])
{ acknowledged: true, insertedIds: { '0': 10, '1': 11 } }
test> db.students.aggregate([{ $lookup: { from: "courses", localField: "courseIds", foreignField: "_id", as: "courses" } }, { $project: { _id: 0, name: 1, courses: "$courses.title" } }])
[
  { name: 'Ada', courses: [ 'Math', 'Code' ] },
  { name: 'Bob', courses: [ 'Code' ] }
]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Embedding unbounded children
  2. Storing id arrays that grow forever
  3. Forgetting to index reference fields
Chapter Summary
  • One-to-one embed
  • One-to-few embed arrays
  • One-to-many reference the parent
  • Many-to-many use id arrays

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.