0
0
MongodbHow-ToBeginner · 3 min read

How to Use $addFields in Aggregation in MongoDB

Use the $addFields stage in a MongoDB aggregation pipeline to add new fields or modify existing ones in documents. It takes an object where keys are field names and values are expressions to compute the new field values. This stage does not remove existing fields but adds or updates fields in each document.
📐

Syntax

The $addFields stage is used inside an aggregation pipeline as an object with field names and expressions. It looks like this:

  • fieldName: The name of the new or existing field to add or update.
  • expression: A MongoDB expression that computes the value for the field.

This stage adds the specified fields to each document passing through the pipeline.

json
{
  $addFields: {
    <field1>: <expression1>,
    <field2>: <expression2>,
    ...
  }
}
💻

Example

This example shows how to add a new field totalPrice by multiplying price and quantity fields in each document.

mongodb
db.orders.aggregate([
  {
    $addFields: {
      totalPrice: { $multiply: ["$price", "$quantity"] }
    }
  }
])
Output
[ { "_id": 1, "item": "apple", "price": 2, "quantity": 5, "totalPrice": 10 }, { "_id": 2, "item": "banana", "price": 1, "quantity": 10, "totalPrice": 10 } ]
⚠️

Common Pitfalls

Common mistakes when using $addFields include:

  • Using $addFields to remove fields (it only adds or updates fields, use $project to remove fields).
  • Referencing fields without $ prefix inside expressions (always prefix field names with $ inside expressions).
  • Trying to add fields outside an aggregation pipeline (it only works inside aggregate()).
mongodb
/* Wrong: Trying to remove a field with $addFields */
db.collection.aggregate([
  { $addFields: { unwantedField: "" } } // This only overwrites, does not remove
])

/* Right: Use $project to remove fields */
db.collection.aggregate([
  { $project: { unwantedField: 0 } }
])
📊

Quick Reference

FeatureDescription
$addFieldsAdds or updates fields in documents during aggregation
Field namesKeys in the $addFields object specify new or existing fields
ExpressionsValues are expressions to compute the field values
Does not remove fieldsUse $project to exclude fields
Used in aggregation pipelineWorks only inside db.collection.aggregate()

Key Takeaways

Use $addFields to add or update fields in aggregation pipeline documents.
Field values in $addFields must be valid MongoDB expressions with $-prefixed field references.
$addFields does not remove fields; use $project to exclude fields.
Always use $addFields inside an aggregation pipeline with db.collection.aggregate().
You can add multiple fields at once by specifying multiple key-value pairs.