$getField
Returns the value of a specified field from a document, with support for dynamically determined field names using expressions and variables.
Syntax
{ $getField: { field: <field_name>, input: <input_expression> } }
Parameters
field
stringrequiredThe name of the field to retrieve, can be a string or expression
input
objectThe input document expression, defaults to $$ROOT (current document)
Examples
Get field with dynamic name
Retrieve field value where field name is determined by another field
Query:
db.products.aggregate([{ $addFields: { fieldValue: { $getField: { field: "$fieldName", input: "$$ROOT" } } } }])
Output:
Document with additional fieldValue containing the dynamically selected field