$lookup से Joins
$lookup same database में एक दूसरे collection के साथ एक left outer join perform करता है।
In this page:
Syntax
{ $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)
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. #}
आम गलतियां
- यह भूल जाना कि result एक array है
- foreignField पर एक index missing होना
- 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: