$addFields (Add Fields)
Last updated: 2026-10-09
$addFields (Add Fields)
$addFields adds new fields to, or overwrites existing fields in, each document while preserving all others. Unlike $project — which drops unlisted fields by default — $addFields only grows the document. New values can be any aggregation expression, often computed from $lookup results. Since MongoDB 3.4 it is equivalent to $set.
| Category | Core Stages |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $addFields: { <newField>: <expression>, ... } }
⚙️ Parameters
| new field | Field names mapped to expressions that reference fields of the input document. |
|---|
Returns:Document stream with added or overwritten fields
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $addFields: add a total field
db.sales.aggregate([
{ $addFields: { total: { $multiply: ['$price', '$qty'] } } }
])
Output:
// All original fields kept, plus total
{ "item": "Pen", "price": 50, "qty": 3, "total": 150 }
📌 Notes
- $addFields never removes existing fields
- Dotted paths like 'order.amount' address embedded fields
- Within one stage you cannot reference fields defined in the same stage
🏷️ Related Tags
💡 Related Cases
Advanced Aggregation Pipelines: Complex Expressions and Transformations
Change Streams: Real-Time Change Monitoring
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $addFields and $set?
ASince MongoDB 3.4 they are fully equivalent; $addFields is the older name.
QCan $addFields reference its new fields?
ANo. Expressions in one stage see only the input document; chain multiple $addFields stages instead.
QDoes $addFields overwrite existing fields?
AYes. A field with an existing name is overwritten.