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.
In this page:
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
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
- Embedding unbounded children
- Storing id arrays that grow forever
- 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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: