Lesson 21 +10 XP

$addFields and $lookup

$addFields and $lookup

$addFields adds new computed fields to each document. $lookup joins documents from another collection.

$addFields - add computed fields

db.restaurants.aggregate([
  {
    $addFields: {
      avgGrade: { $avg: "$grades.score" }
    }
  },
  { $project: { name: 1, avgGrade: 1 } },
  { $limit: 5 }
])

Each restaurant gets a new avgGrade field equal to the average of its grades.score array.

  • $addFields keeps all existing fields and only adds new ones.
  • $project restricts fields; $addFields just adds.
  • Inside $addFields, $avg works across an array within one document (inside $group it works across documents in a group).

$lookup - join another collection

$lookup performs a left outer join with another collection in the same database:

db.comments.aggregate([
  {
    $lookup: {
      from: "movies",
      localField: "movie_id",
      foreignField: "_id",
      as: "movie_details"
    }
  },
  { $limit: 1 }
])

The four $lookup fields

FieldMeaning
fromCollection to join with (same database)
localFieldField in the primary collection
foreignFieldField in the from collection
asName of the new field holding the matches

The result of $lookup is always an array, even when there's only one match.

TL;DR

  • $addFields adds computed fields, keeping existing ones.
  • $lookup joins another collection (same database).
  • Requires from, localField, foreignField, as; result is an array.