$addFields, $replaceRoot, and $mergeObjects
Learners will add computed fields, promote nested sub-documents to the root level, and merge objects within the pipeline.
Three Reshaping Stages
While $project is the primary document-reshaping tool, three additional stages offer more targeted transformations: $addFields adds new fields while preserving all existing ones, $replaceRoot promotes a sub-document to become the new root document, and $mergeObjects merges multiple objects into one. Together they cover reshaping patterns that would be verbose or impossible with $project alone.
$addFields: Adding Without Dropping
$addFields (also available as its alias $set) passes through all existing document fields and adds or overwrites only the specified fields. This is the key difference from $project in inclusion mode, where you must explicitly list every field you want to keep. Use $addFields whenever you want to enrich a document with computed fields without listing every existing field.
// $addFields preserves all existing fields
db.products.aggregate([{
$addFields: {
// Add computed fields; all original fields (name, price, etc.) are kept
totalWithTax: { $multiply: ['$price', 1.1] },
priceLabel: { $concat: ['$', { $toString: '$price' }] },
isExpensive: { $gt: ['$price', 1000] }
}
}]);
// All original product fields PLUS the three new computed fieldsAll lessons in this course
- $lookup: Joining Collections in the Pipeline
- $unwind: Deconstructing Array Fields
- $addFields, $replaceRoot, and $mergeObjects
- $out and $merge: Writing Pipeline Results