← Back to MongoDB Course | Chapter 7: Aggregation | Lesson 6 of 7

$lookup से Joins

$lookup same database में एक दूसरे collection के साथ एक left outer join perform करता है।

In this page:

  1. $lookup (Joins)
Syntax
javascript
{ $lookup: {
    from: "other_collection",
    localField: "local_field",
    foreignField: "foreign_field",
    as: "result_array"
} }

$lookup (Joins)

$lookup from, localField, foreignField, और as लेता है, और हर input document में matching foreign documents का एक array add करता है।

एक empty array मतलब कोई match नहीं। Array flatten करने के लिए इसे $unwind के साथ pair करें।

Frequent joins शायद data embed करने का suggest करें इसकी बजाय।

Note: fast lookups के लिए foreignField index करें।

उदाहरण: $lookup (joins)

bash
test> db.customers.insertMany([{ _id: 1, name: "Ada" }, { _id: 2, name: "Bob" }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
test> db.orders.insertMany([{ _id: 10, customerId: 1, total: 50 }, { _id: 11, customerId: 1, total: 20 }, { _id: 12, customerId: 3, total: 5 }])
{ acknowledged: true, insertedIds: { '0': 10, '1': 11, '2': 12 } }
test> db.orders.aggregate([
...   { $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customer" } },
...   { $project: { total: 1, customer: "$customer.name" } }
... ])
[
  { _id: 10, total: 50, customer: [ 'Ada' ] },
  { _id: 11, total: 20, customer: [ 'Ada' ] },
  { _id: 12, total: 5, customer: [] }
]

⚠️ 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. यह भूल जाना कि result एक array है
  2. foreignField पर एक index missing होना
  3. good schema design की बजाय हर जगह joins इस्तेमाल करना
चैप्टर सारांश
  • $lookup collections join करता है
  • from, localField, foreignField, as fields इस्तेमाल होते हैं
  • Result एक array है
  • Foreign field index करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

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.