$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

fieldstringrequired

The name of the field to set, can be a string or expression

inputobjectrequired

The input document to modify

valueobjectrequired

The 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

Update existing field

Modify an existing field value using setField

Query:

db.products.aggregate([{ $addFields: { updated: { $setField: { field: "status", input: "$$ROOT", value: "processed" } } } }])

Output:

Document with updated field containing document with modified status

Remove field conditionally

Remove field from document using $$REMOVE value

Query:

db.products.aggregate([{ $addFields: { cleaned: { $setField: { field: "tempField", input: "$$ROOT", value: "$$REMOVE" } } } }])

Output:

Document with cleaned field containing document without tempField

Related