TExcelTAD
Home › MongoDB › Aggregation $lookup

Aggregation $lookup

$lookup joins documents from another collection in the same database. For each input document it finds the matching documents in the other collection and adds them as an array field. It behaves like a SQL LEFT OUTER JOIN: documents without a match are kept, with an empty array.

js
{ $lookup: {
    from: '<other collection>',
    localField: '<field in the input documents>',
    foreignField: '<field in the other collection>',
    as: '<name of the new array field>'
} }

Joining orders to customers

Orders store only customerId. To show the customer's name next to each order:

mongosh · try it yourself
print(db.orders.aggregate([
  { $match: { status: 'shipped' } },
  { $lookup: { from: 'customers', localField: 'customerId', foreignField: '_id', as: 'customer' } },
  { $project: { total: 1, 'customer.name': 1, 'customer.tier': 1 } }
]).toArray());
[
  {
    _id: 1010,
    total: 49,
    customer: [ { name: 'Margaret Hamilton', tier: 'silver' } ]
  },
  {
    _id: 1012,
    total: 48,
    customer: [ { name: 'Edsger Dijkstra', tier: 'silver' } ]
  },
  {
    _id: 1013,
    total: 28.5,
    customer: [ { name: 'Ada Lovelace', tier: 'gold' } ]
  }
]

customer is an array even though there is at most one match, because $lookup can't know that _id is unique in the joined collection.

Turning the array into a field

Two common ways to flatten a one-element array: $unwind, or $first inside $set:

mongosh · try it yourself
db.orders.aggregate([
  { $match: { status: 'shipped' } },
  { $lookup: { from: 'customers', localField: 'customerId', foreignField: '_id', as: 'customer' } },
  { $set: { customer: { $first: '$customer' } } },
  { $project: { _id: 1, name: '$customer.name', city: '$customer.address.city', total: 1 } }
]).forEach(o => print(o._id, o.name, '(' + o.city + ')', o.total));
1010 Margaret Hamilton (Boston) 49
1012 Edsger Dijkstra (Rotterdam) 48
1013 Ada Lovelace (London) 28.5

The other direction: one-to-many

Looking up from customers to orders gives each customer the array of their orders. Customers without orders get an empty array, which makes it easy to find them:

mongosh · try it yourself
db.customers.aggregate([
  { $lookup: { from: 'orders', localField: '_id', foreignField: 'customerId', as: 'orders' } },
  { $project: { name: 1, orderCount: { $size: '$orders' } } },
  { $match: { orderCount: 0 } }
]).forEach(c => print(c._id, c.name));
4 Linus Torvalds
8 Donald Knuth
12 Radia Perlman

Joining on array elements

If localField is an array, $lookup matches any element. items.productId is the array of product ids in an order, so this pulls in the current product documents, for example to compare the price paid with today's stock:

mongosh · try it yourself
print(db.orders.aggregate([
  { $match: { _id: 1010 } },
  { $lookup: { from: 'products', localField: 'items.productId', foreignField: '_id', as: 'products' } },
  { $project: { products: { name: 1, stock: 1 } } }
]).toArray());
[
  {
    _id: 1010,
    products: [
      { name: 'Ethiopia Yirgacheffe', stock: 12 },
      { name: 'Masala Chai', stock: 18 }
    ]
  }
]

Lookup with a pipeline

For conditions beyond equality, or to shape the joined documents, give $lookup its own pipeline. let passes fields of the input document into it as variables ($name). Here each gold customer gets only their delivered orders, newest first:

mongosh · try it yourself
db.customers.aggregate([
  { $match: { tier: 'gold' } },
  { $lookup: {
      from: 'orders',
      let: { cid: '$_id' },
      pipeline: [
        { $match: { $expr: { $eq: ['$customerId', '$cid'] }, status: 'delivered' } },
        { $sort: { date: -1 } },
        { $project: { _id: 1, total: 1 } }
      ],
      as: 'delivered'
  } },
  { $project: { name: 1, delivered: 1 } }
]).forEach(c => print(c.name, c.delivered));
Ada Lovelace [ { _id: 1005, total: 59 }, { _id: 1001, total: 55 } ]
Grace Hopper [ { _id: 1008, total: 59.5 }, { _id: 1002, total: 45 } ]
Barbara Liskov []

Barbara Liskov's only order was cancelled, so her array is empty: the lookup still keeps her.

Tip: $lookup runs a query on the other collection for every input document. Index the foreignField (here orders.customerId) and $match before the $lookup to keep it fast. If you join the same data on every read, consider embedding it instead (see Data Modeling).

Test yourself

What type is the field created by $lookup's as?

  1. A single document
  2. An array
  3. A string
  4. It depends on the number of matches

What happens to an input document with no match in the from collection?

  1. It is removed
  2. It is kept with an empty array
  3. The pipeline fails
  4. It gets a null field

Inside a $lookup pipeline, how do you refer to a variable defined in let: { cid: '$_id' }?

  1. '$cid'
  2. '$cid'
  3. 'cid'
  4. '$let.cid'