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 :-
  • Step 1: Identify the source collection
  • Step 2: Specify the foreign collection to join
  • Step 3: Define the local field (from source collection)
  • Step 4: Define the foreign field (from foreign collection)
  • Step 5: Specify the output array field name
  • 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 :-
  • Step 1: Identify collections to join
  • Step 2: Define pipeline stages for lookup
  • Step 3: Set up match conditions
  • Step 4: Add additional pipeline stages if needed
  • Step 5: Specify output structure
  • 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"
    }
    }
    ])