#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 9 of 27medium

How does $lookup work in MongoDB?

Understanding joins with $lookup.

What You'll Learn

  • Basic $lookup syntax
  • Pipeline $lookup
  • Performance considerations

Basic $lookup

code.jsJavaScript
// orders collection
{ _id: 1, userId: ObjectId("user1"), total: 99.99 }

// users collection
{ _id: ObjectId("user1"), name: "John" }

// Join orders with users
db.orders.aggregate([
  {
    $lookup: {
      from: "users",           // Collection to join
      localField: "userId",    // Field from orders
      foreignField: "_id",     // Field from users
      as: "user"               // Output array field
    }
  },
  { $unwind: "$user" }  // Convert array to object
]);

// Result
{
  _id: 1,
  userId: ObjectId("user1"),
  total: 99.99,
  user: { _id: ObjectId("user1"), name: "John" }
}

Pipeline $lookup

code.jsJavaScript
db.orders.aggregate([
  {
    $lookup: {
      from: "products",
      let: { orderItems: "$items" },
      pipeline: [
        { $match: {
            $expr: { $in: ["$_id", "$$orderItems"] }
        }},
        { $project: { name: 1, price: 1 } }
      ],
      as: "productDetails"
    }
  }
]);

Multiple Lookups

code.jsJavaScript
db.orders.aggregate([
  { $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" }},
  { $lookup: { from: "products", localField: "productId", foreignField: "_id", as: "product" }},
  { $unwind: "$user" },
  { $unwind: "$product" }
]);

Performance Tips

  • Index foreign fields
  • Use $match before $lookup
  • Limit fields with $project
  • Consider denormalization for frequent joins