Join collections with $lookup

Bring together documents of two collections in one query.

Bring together documents of two collections in a single query with $lookup, like a join.

Requirements

  • A connection with a user that has read on the database. On both collections.

Join by a field

JavaScript
db.orders.aggregate([
  { $match: { status: "paid" } },
  { $lookup: { from: "customers", localField: "customer", foreignField: "_id", as: "customerData" } },
  { $unwind: "$customerData" },
]);

Join with your own conditions

JavaScript
db.customers.aggregate([
  {
    $lookup: {
      from: "orders",
      let: { id: "$_id" },
      pipeline: [{ $match: { $expr: { $eq: ["$customer", "$$id"] } } }, { $limit: 5 }],
      as: "latest",
    },
  },
]);

Check

Each document of the result carries in customerData the document of the customer of its order, taken from customers.

Common problems

  • The join is slow because foreignField has no index in the other collection. Create one on that field.

See also