$setField (Set Field by Name)
Last updated: 2026-10-09
$setField (Set Field by Name)
$setField adds or updates a named field in a document and returns a new document without mutating the input. The syntax is { $setField: { field: field-name, input: document, value: expression } }, and field accepts a dynamic expression. A null value removes the field. It is used when field names contain special characters or must be computed dynamically. A null or missing input returns null. Unlike the $set stage, $setField works inside nested expressions and supports dynamic field names.
| Category | Literal, Variable & Object |
|---|---|
| MongoDB Version | 5.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $setField: { field: <field-name>, input: <document-expression>, value: <expression> } }
⚙️ Parameters
| field | The field name as a string or an expression resolving to a string. |
|---|---|
| input | Target document; a null or missing input yields null. |
| value | The value to set; null removes the field. |
Returns:A new document with the field set; null when input is null or missing
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $setField: add a tax rate field to each order
db.orders.aggregate([
{ $project: {
doc: { $setField: { field: 'taxRate', input: '$$CURRENT', value: 0.08 } }
} }
])
Output:
{ '_id': 1, 'doc': { '_id': 1, 'price': 100, 'taxRate': 0.08 } }
{ '_id': 2, 'doc': { '_id': 2, 'price': 50, 'taxRate': 0.08 } }
📌 Notes
- Returns a new document; the input is not mutated
- A null value removes the field
- Pairs with $getField for dynamic field names
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QDoes $setField modify the original document?
ANo — documents are immutable in pipelines; $setField returns a new document.
QHow do I remove a field with $setField?
ASet value to null and the field is removed.
QHow do $setField and the $set stage differ?
A$set only handles static field names, while $setField supports dynamic names and nested expressions.