Loading lessons...
$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.
$addFieldskeeps all existing fields and only adds new ones.$projectrestricts fields;$addFieldsjust adds.- Inside
$addFields,$avgworks across an array within one document (inside$groupit 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
| Field | Meaning |
|---|---|
| from | Collection to join with (same database) |
| localField | Field in the primary collection |
| foreignField | Field in the from collection |
| as | Name of the new field holding the matches |
The result of $lookup is always an array, even when there's only one match.
TL;DR
$addFieldsadds computed fields, keeping existing ones.$lookupjoins another collection (same database).- Requires
from,localField,foreignField,as; result is an array.