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

One-to-One, One-to-Many और Many-to-Many

Relationships embedding से या ids store करके model होते हैं, कितने items involved हैं इसके आधार पर।

One-to-One/One-to-Many/Many-to-Many

One-to-one: embed करें। One-to-few: एक array embed करें। One-to-many: many side से reference करें या अगर bounded हो तो embed करें। One-to-squillions: हर child में parent id store करें। Many-to-many: एक या दोनों sides पर ids के arrays, या एक linking collection।

Note: बड़ी counts वाले one-to-many के लिए, child documents में parent id रखें।

उदाहरण: 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. #}
आम गलतियां
  1. Unbounded children embed करना
  2. हमेशा बढ़ने वाले id arrays store करना
  3. reference fields index करना भूल जाना
चैप्टर सारांश
  • One-to-one embed करें
  • One-to-few arrays embed करें
  • One-to-many parent reference करें
  • Many-to-many 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.