0PricingLogin
MongoDB Academy · Lesson

$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 fields

All lessons in this course

  1. $lookup: Joining Collections in the Pipeline
  2. $unwind: Deconstructing Array Fields
  3. $addFields, $replaceRoot, and $mergeObjects
  4. $out and $merge: Writing Pipeline Results
← Back to MongoDB Academy