1. MongoDB $lookup Aggregation
Definition
The $lookup stage in MongoDB's aggregation pipeline performs a left outer join to another collection in the same database. It allows you to combine documents from multiple collections based on specified conditions, similar to JOIN operations in SQL databases.
Algorithm 1: Basic $lookup Usage :-
Example 1: Basic Collection Join
// Join orders with customers collection
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerDetails"
}
}
])
Algorithm 2: Advanced $lookup Pipeline :-
Example 2: Pipeline-based Lookup
// Complex lookup with pipeline
db.orders.aggregate([
{
$lookup: {
from: "products",
let: { order_item: "$item", order_qty: "$quantity" },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ["$item", "$$order_item"] },
{ $gte: ["$inStock", "$$order_qty"] }
]
}
}
},
{ $project: { item: 1, price: 1, inStock: 1 } }
],
as: "matchedProducts"
}
}
])