$setField
Adds, updates, or removes fields in a document, allowing dynamic field manipulation with support for computed field names and conditional operations.
Syntax
{ $setField: { field: <field_name>, input: <input_document>, value: <field_value> } }
Parameters
field
stringrequiredThe name of the field to set, can be a string or expression
input
objectrequiredThe input document to modify
value
objectrequiredThe value to set for the field, use $$REMOVE to delete field
Examples
Add new field dynamically
Add a new field with computed name and value
Query:
db.products.aggregate([{ $addFields: { result: { $setField: { field: "computedPrice", input: "$$ROOT", value: { $multiply: ["$price", 1.1] } } } } }])
Output:
Document with result containing the original document plus computedPrice field