Computed Fields in $project
$project can do more than pick fields. It can also create new fields that are calculated from the document. To use a field's value in a calculation, write its name in quotes with a dollar sign in front: "$year" means "the value of the year field".
db.movies.aggregate([
{ $match: { director: "Christopher Nolan" } },
{ $project: {
_id: 0,
title: 1,
age: { $subtract: [2025, "$year"] },
outOf5: { $divide: ["$rating", 2] }
} }
])
Output:
[
{ title: 'Inception', age: 15, outOf5: 4.4 },
{ title: 'Interstellar', age: 11, outOf5: 4.35 },
{ title: 'Dunkirk', age: 8, outOf5: 3.9 }
]
age is 2025 minus the movie's year, which is how old the movie was in 2025. outOf5 is the rating divided by 2, so the rating is out of 5 instead of 10. These new fields exist only in the result. The documents in the collection do not change.
The math operators $add, $subtract, $multiply and $divide all take their values in an array. A value can be a number or a field, like "$rating".
$concat joins pieces of text into one string:
db.movies.aggregate([
{ $match: { year: 2014 } },
{ $project: {
_id: 0,
label: { $concat: ["$title", " by ", "$director"] }
} }
])
Output:
[
{ label: 'Interstellar by Christopher Nolan' },
{ label: 'Whiplash by Damien Chazelle' }
]
" by " is plain text, and "$title" and "$director" are fields. $concat works only with text. A number field like "$year" must be turned into text first.
In the exercise, show each movie's votes in thousands.